spring cloud整合OpenFeign
spring cloud整合OpenFeign
pom.xml配置
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-openfeign-core -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign-core</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
主启动类
使用@EnableFeignClients开启Feign功能,这里使用Eureka做服务注册所以使用@EnableEurekaClient注解
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class OrderApplication81 {
public static void main(String[] args) {
SpringApplication.run(OrderApplication81.class,args);
}
}
定义service接口
使用openFeign需要编写接口,然后通过使用@FeignClient注解。接口的方法写提供者的接口即可,OpenFeign就会通过这些来生成接口的代理对象。(之所以@Component标注的接口能生成Bean,是因为在生成Bean的过程中有AOP,AOP后生成的是代理对象。)springcloud整合OpenFeign,原理就是通过AOP进行横切增强然后生成代理对象。
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentOpenfeginService {
@GetMapping("/payment/get/{id}")
public ResponseMessage getPaymentById(@PathVariable("id") int id);
}
controller编写
通过@Resource自动注入PaymentOpenfeginService接口的代理对象,这个代理对象由spring cloud openFeign生成。这个代理对象是通过动态代理生成的,通过AOP实现代码增强。
@RestController
@Slf4j
public class OrderController {
@Resource
private PaymentOpenfeginService paymentOpenfeginService;
@GetMapping("/comsumer/payment/get/{id}")
public ResponseMessage getPaymentById(@PathVariable("id") int id){
return paymentOpenfeginService.getPaymentById(id);
}
}
openfeign超时控制
通过application.yml中添加以下配置,配置openfeign连接超时控制。
feign:
httpclient:
connection-timeout: 2000
openFeign日志功能
通过指定feign接口的日志等级,通知feign的日志
logging:
level: #指定feign接口的日志等级
com.example.springcloud.service.PaymentOpenfeginService: debug
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)