基础概念
OpenFeign是一个声明式的WebService客户端,Feign是一个声明式的web服务客户端,让编写web服务客户端变得非常容易,只需创建一个接口并在接口上添加注解即可。
openfegin官网地址
使用案例
openfegin的使用比较简单,微服务调用接口+@FeignClient就可以实现。
这里我们还是用eureka作为注册中心
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
主启动类:
@EnableFeignClients
新建一个接口用于调用服务
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface Service {
@GetMapping(value = "/payment/get/{id}")
CommonResult getPaymentById(@PathVariable("id") Long id);
}
新建controller
@RestController
public class ConsumerController {
@Resource
Service service;
@GetMapping("/consumer/feign/{id}")
public CommonResult getFeign(@PathVariable("id") Long id) {
return service.getPaymentById(id);
}
}
调用结果:
注:由于feign自己就集成了Ribbon,多所以它默认就有负载均衡的功能。
在某些场景我们的业务处理可能需要一定的时间, 有可能会超时,超时就会报错需要我们进行配置, 由于openfeign的底层是由ribbon进行负载均衡所以添加ribbon的配置。
ribbon:
ReadTimeout: 5000
ConnectTimeout: 5000
openfegin日志:
我们新建配置类:
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL; // 在这里设置我们的日志级别
}
}
同时我们需要在配置文件指定,我们feign的客户端在哪里
logging:
level:
com.atguigu.springcloud.service.PaymentFeignService: debug
注:此文章部分代码图片来源于尚硅谷视频教学