是什么
把需要暴露的api使用接口来暴露,客户端需要调用的时候,直接查看这个接口中有没有就可以了
通用步骤
架构说明
common模块
common 引入 openfeign
新建服务接口类
@FeignClient(value = "cloud-payment-service") // 服务名
public interface PayFeignApi {
@PostMapping("/pay/add")
public Result<Integer> addPay(@RequestBody PayDTO payDTO);
@GetMapping("/pay/get/{id}")
public Result<PayDTO> getById(@PathVariable("id") Integer id); // 必须指明 PathVariable 的 value
@GetMapping("/pay/getInfo")
public Result<String> getInfo();
}
客户端
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
主启动类 @EnableFeignClients
使用
@RestController
public class OrderController {
@Resource
private PayFeignApi payFeignApi;
@GetMapping("/consumer/pay/add")
public Result addOrder(PayDTO payDTO) {
return payFeignApi.addPay(payDTO);
}
@GetMapping("/consumer/pay/get/{id}")
public Result<PayDTO> getPayByOrderNo(@PathVariable("id") Integer id) {
return payFeignApi.getById(id);
}
@GetMapping("/consumer/pay/getInfo")
public Result<String> getInfoByConsul() {
return payFeignApi.getInfo();
}
}
最后一个案例可以看到,openfeign 天生支持负载均衡
OpenFeign高级特性
日志打印
// 日志记录级别
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
超时控制
测试超时时间异常
@GetMapping("/consumer/pay/getInfo")
public Result<String> getInfoByConsul() {
Result<String> result = null;
try {
System.out.println("调用开始: " + DateUtil.now());
result = payFeignApi.getInfo();
} catch (Exception e) {
e.printStackTrace();
System.out.println("调用结束: " + DateUtil.now());
Result.fail(ReturnCodeEnum.RC500.getCode(), e.getMessage());
}
return result;
}
read-timeout 默认 60s
如何调整
全局配置
调整后测试,发现3s后就异常返回
手动配置(服务级别)
同时存在,细粒度的覆盖粗粒度的
重试机制
性能优化HttpClient5替换
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-hc5</artifactId>
<version>13.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.3.1</version>
</dependency>
spring:
cloud:
openfeign:
httpclient:
hc5:
enabled: true
HttpClient5 开启
替换以后
请求回应压缩
spring:
cloud:
openfeign:
compression:
request:
enabled: true
mime-types: text/xml,application/xml,application/json
min-request-size: 2048
response:
enabled: true