简介
Feign是Spring Cloud提供的一个声明式的伪Http客户端, 它使得调用远程服务就像调用本地服务一样简单, 只需要创建一个接口并添加一个注解即可。
Nacos很好的兼容了Feign, Feign默认集成了 Ribbon, 所以在Nacos下使用Fegin默认就实现了负载均衡的效果。
Fegin的使用:加入pom依赖
<!--fegin组件-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启动类加入Fegin注解
@SpringBootApplication @EnableDiscoveryClient //服务注册 @EnableFeignClients //开启fegin public class OrderApplication {···}
创建商品服务的api接口并使用Fegin实现微服务调用
@FeignClient("service-product")//声明调用的提供者的name
public interface ProductApiService {
/**
* 指定调用提供者的哪个方法
* @FeignClient+@GetMapping 就是一个完整的请求路径 http://service-product/product/{pid}
* @param pid
* @return
*/
@GetMapping("/product/{pid}")
Product getByPid(@PathVariable("pid") Integer pid);
}
改造下单方法测试
@Autowired private ProductApiService productApiService; /** * 基于fegin实现远程服务调用 * @param pid * @return */ @GetMapping("/prod/{pid}") public Order order(@PathVariable("pid") Integer pid){ log.info(">>>客户下单,调用商品微服务查询商品信息<<<"); Product product = productApiService.getByPid(pid); log.info(">>商品信息,查询结果:" + JSON.toJSONString(product)); Order order = new Order(); order.setUid(1); order.setUsername("测试用户1"); order.setPid(product.getPid()); order.setPname(product.getPname()); order.setPprice(product.getPprice()); order.setNumber(1); // orderService.save(order); return order; }
启动服务测试接口是否正常调用
