一、Feign 简介
在上一个用例中,我们使用 Ribbon + RestTemplate 实现服务之间的远程调用,实际上每一个调用都是模板化的内容,所以 Spring Cloud Feign 在此基础上进行了进一步的封装。我们只需要定义一个接口并使用 Feign 注解的方式来进行配置,同时采用 springMvc 注解进行参数绑定就可以完成服务的调用。Feign 同时还内置实现了负载均衡、服务容错等功能。
二、项目结构
- common:公共的接口和实体类;
- consumer:服务的消费者,采用 Feign 调用产品服务;
- producer:服务的提供者;
- eureka:注册中心。
三、服务提供者的实现
3.1 定义服务
产品服务由 ProductService
提供,并通过 ProducerController
将服务暴露给外部调用:
ProductService.java:
/**
* @author : heibaiying
* @description : 产品提供接口实现类
*/
@Service
public class ProductService implements IProductService, ApplicationListener<WebServerInitializedEvent> {
private static List<Product> productList = new ArrayList<>();
public Product queryProductById(int id) {
return productList.stream().filter(p->p.getId()==id).collect(Collectors.toList()).get(0);
}
public List<Product> queryAllProducts() {
return productList;
}
@Override
public void saveProduct(Product product) {
productList.add(product);
}
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
int port = event.getWebServer().getPort();
for (long i = 0; i < 20; i++) {
productList.add(new Product(i, port + "产品" + i, i / 2 == 0, new Date(), 66.66f * i));
}
}
}
ProducerController.java:
@RestController
public class ProducerController implements