OpenFeign 使用记录

2 minute

为什么要使用 OpenFeign

之前在消费端使用 RestTemplate 时,每次请求都要进行诸如:

1restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);

这样的调用,需要指定较多参数,当一个接口调用中需要非常多这样的请求时,会比较繁琐,而且这种方式不够抽象。

OpenFegin 利用面向接口编程的思想,抽象化,简化了上述操作。

使用 OpenFeign

依赖导入

1<dependency>
2    <groupId>org.springframework.cloud</groupId>
3    <artifactId>spring-cloud-starter-openfeign</artifactId>
4</dependency>

配置信息

除了基本配置内容外,注意以下配置:

 1feign:
 2# 设置feign客户端超时时间(默认为1秒)
 3client:
 4    config:
 5    default:
 6        ConnectTimeOut: 10000
 7        ReadTimeOut: 10000
 8# 针对每个接口设置日志监控级别
 9logging:
10level:
11    com.jzh.springcloud.service.PaymentService: debug # feign日志以什么级别监控端口

编写接口

首先在启动类开启 @EnableFeignClients 注解,接着编写服务接口:

  • 添加 @FeignClient 注解,值为对应微服务名;
  • 方法对应微服务 Controller 下的方法即可。
1@Component
2@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
3public interface PaymentService {
4    @GetMapping("/payment/get/{id}")
5    CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
6
7    @PostMapping("/payment/create")
8    CommonResult<Integer> createPayment(@RequestBody Payment payment);
9}

然后实现该接口编写具体操作逻辑即可,这里省略了。

调用接口

注入 PaymentService 接口,然后即可调用它的方法。

 1@RestController
 2@Slf4j
 3public class PaymentController {
 4    @Resource
 5    private PaymentService paymentService;
 6
 7    @PostMapping("/consumer/payment/create")
 8    public CommonResult<Integer> create(@RequestBody Payment payment) {
 9        return paymentService.createPayment(payment);
10    }
11
12    @GetMapping("/consumer/payment/get/{id}")
13    public  CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
14        return paymentService.getPaymentById(id);
15    }
16}

配置日志输出级别

返回 Logger.Level 对象,放入 spring 容器中:

1@Configuration
2public class FeignConfig {
3    @Bean
4    Logger.Level feignLogLevel() {
5        return Logger.Level.BASIC;
6    }
7}