前言
Feign是一个声明式的web service客户端,用它可以更容易编写web服务客户端。 它使你调用远程方法就像调用本地方法一样简单,不需要IP和端口,也不需要在单独写一个http请求工具类。并且feign集成了ribbon,实现了负载均衡。
一、引入Feign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
二、编写代码
1.启动类上加注解EnableFeignClients
在启动类处加上如下的注解:
@SpringBootApplication
@EnableFeignClients
public class FeignApplication {
public static void main(String[] args) {
SpringApplication.run(FeignApplication.class, args);
}
}
2.接口类上加注解FeignClient
PaymentService接口代码,这个接口的代码可以写到一个公共包里,让feign应用和服务端应用一同继承或者实现。
public interface PaymentService {
CommonResult<Payment> getPaymentById();
}
在feign工程增加代码,示例如下:
@FeignClient("backend-service")
public interface PaymentServiceFeign extends PaymentService {
@Override
@RequestMapping(method = RequestMethod.GET, value = "/api/payment/getPaymentById")
CommonResult<Payment> getPaymentById();
}
调用的时候就可以像请求普通的接口一样访问就可以,示例如下
@RestController
public class PaymentController {
@Resource
private PaymentServiceFeign paymentServiceFeign;
@GetMapping("/feign")
public String getPaymentByFeign() {
CommonResult<Payment> result = paymentServiceFeign.getPaymentById();
return JSONUtil.toJsonStr(result); // JSONUtil hutool的包
}
}
3.测试
总结
OpenFeign虽然集成了Ribbon,但Ribbon已经处于维护模式,应该避免使用Ribbon,官方使用Spring Cloud LoadBalancer。