Feign是一个声明式Web服务客户端,能让编写web客户端更加简单,创建一个接口并在上面添加注解去使用Feign,它支持Feign注解和JAX-RS注解。Feign也支持可插拔式的编码器和解码器,Feign 默认整合了Eureka和Ribbon实现客户端负载均衡。
Feign核心是使得编写Java Http客户端变得更容易,使用接口和注解(类似Mybatis中Dao和@Mapper)来完成对服务提供者接口的绑定,从而简化操作。Feign集成了Ribbon,可以利用Ribbo实现负载均衡。
官方文档:
http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign
以下内容是基于上一节的工程,使用Feign 实现服务间通讯。
源码下载:https://github.com/hnyydp/microservice
(1)、模仿microservice-dept-consumer-80 新建一个消费者module模块 microservice-dept-consumer-feign
,添加Feign依赖
pom.xml
<!-- Feign依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
(2)、修改配置文件
server:
context-path: /
port: 80
spring:
application:
name: microservice-dept-consumer-feign #服务名
eureka:
client:
register-with-eureka: false #false表示不向注册中心注册自己,因为本身应用就是注册中心
service-url:
#集群配置
defaultZone: http://eureka-server-5001.com:5001/eureka/,http://eureka-server-5002.com:5002/eureka/,http://eureka-server-5003.com:5003/eureka/
(3)、修改api模块microservice-common
,新建DeptClientService.java
接口
/**
* 声明feign接口
* @author dave
*
*/
@FeignClient(value = "MICROSERVICE-DEPT") // 指定调用哪个服务
public interface DeptClientService {
@GetMapping("/depts")
public List<Dept> depts();
@GetMapping("/dept/{id}")
public Dept dept(@PathVariable(value = "id") Integer id);
@PostMapping("/dept")
public Dept insert(@RequestBody Dept dept);
@PutMapping("/dept")
public Dept update(@RequestBody Dept dept);
@DeleteMapping("/dept/{id}")
public boolean delete(@PathVariable(value = "id") Integer id);
}
(4)创建Controller类DeptConsumerController.java
@RequestMapping("/consumer")
@RestController
public class DeptConsumerController {
@Autowired
private DeptClientService deptClientService; //使用Feign接口
@GetMapping("/depts")
public List<Dept> depts() {
return deptClientService.depts();
}
@GetMapping("/dept/{id}")
public Dept dept(@PathVariable(value = "id") Integer id) {
return deptClientService.dept(id);
}
@PostMapping("/dept")
public Dept insert(@RequestBody Dept dept) {
return deptClientService.insert(dept);
}
@PutMapping("/dept")
public Dept update(@RequestBody Dept dept) {
return deptClientService.update(dept);
}
@DeleteMapping("/dept/{id}")
public boolean delete(@PathVariable(value = "id") Integer id) {
try {
deptClientService.delete(id);
return true;
} catch (Exception e) {
return false;
}
}
}
(5)创建主启动类DeptConsumerFeignApplication.java
,开启Feign
@EnableFeignClients //开启Feign
@EnableEurekaClient
@SpringBootApplication
public class DeptConsumerFeignApplication {
public static void main(String[] args) {
SpringApplication.run(DeptConsumerFeignApplication.class, args);
}
}
(6)分别启动Eureka sever、服务提供者 和 microservice-dept-consumer-feign,访问接口默认会使用轮询策略。