feign是声明式的web service客户端,它让服务之间的调用变得更简单了,类似controller层调用service层,SpringCloud集成了Ribbon和Eureka,可在使用feign时提供负载均衡的http客户端
只需要创建一个接口,然后添加注解即可!
feign主要是社区,大家都习惯面向接口编程,这个是很多开发人员的规范,调用微服务访问的两种方法
? 1.微服务名字【Ribbon】
? 2.接口和注释【feign】
? 1)导入依赖
<!--Feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
? 2)添加feign服务(接口)
package com.mjh.springcloud.service;
import com.mjh.springcloud.pojo.Dept;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.List;
@FeignClient(value = "SPRINGCLOUD-PRIVIDER-DEPT")
public interface DeptClientService {
@GetMapping("/dept/add")
public Dept addDept(Dept dept);
@GetMapping("/dept/queryById/{id}")
public Dept queryById(@PathVariable("id") Long id);
@PostMapping("/dept/list")
public Dept queryAll();
}
? 3)让客户端调用feign接口
package com.mjh.springcloud.controller;
import com.mjh.springcloud.pojo.Dept;
import com.mjh.springcloud.service.DeptClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
public class DeptConsumerController {
@Autowired
private DeptClientService Service=null;
@RequestMapping("/consumer/dept/add")
public boolean add(Dept dept){
return this.Service.addDept(dept);
}
@RequestMapping("/consumer/dept/queryById/{id}")
public Dept queryById(@PathVariable("id") Long id){
//服务端给你什么方法你就调用什么方法
return this.Service.queryById(id);
}
@RequestMapping("/consumer/dept/list")
public List<Dept> list(){
return this.Service.queryAll();
}
}
? 4)把刚才写的feign扫进来
@SpringBootApplication
@EnableEurekaClient //Eureka客户端
@EnableFeignClients(basePackages={"com.mjh.springcloud"})
@ComponentScan("com.mjh.springcloud")
public class FeignDeptConsumer_80 {
public static void main(String[] args) {
SpringApplication.run(FeignDeptConsumer_80.class,args);
}
}
原文:https://www.cnblogs.com/mjjh/p/13392935.html