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