什么是Spring Cloud OpenFeign
Spring Cloud OpenFeign是基于Netflix Feign实现的,它整合了Spring Cloud Ribbon 与 Spring Cloud Hystrix。它只需要创建一个接口并用注解的方式来配置它,即可完成对服务提供方的接口绑定。进一步的简化了客户端调用服务的开发量,让远程服务的调用就像是调用本地方法一样,对开发来说更加友好。同时它还有很多其他的功能,比如请求压缩、日志配置等。
OpenFeign的应用
- 在服务消费者中添加Feign的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 定义一个服务调用的接口,在接口上加上**@FeignClient**注解,在注解中指定服务提供者的服务名,同时定义一个与服务提供者一样的接口方法。
package com.wxw.example.springcloudconsumer.controller;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient("provider-service")
public interface IHelloControllerFeign {
@RequestMapping("/hello")
String hello();
}
- 在启动类中添加**@EnableFeignClients**注解启动Feign的功能
@SpringBootApplication
@EnableFeignClients
public class SpringCloudConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudConsumerApplication.class, args);
}
}
- 服务调用者添加服务调用逻辑
package com.wxw.example.springcloudconsumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TsetFeignController {
@Autowired
IHelloControllerFeign iHelloControllerFeign;
@RequestMapping("/testFeign")
public String testFeign(){
return iHelloControllerFeign.hello();
}
}
OpenFeign的其他特性
Gzip压缩
在配置文件中可以配置Feign的压缩特性
# 请求压缩
feign.compression.request.enabled=true
# 执行压缩的大小阈值
feign.compression.request.min-request-size=2048
# 响应请求压缩
feign.compression.response.enabled=true
# 压缩的类型
feign.compression.request.mime-types=text/xml
OpenFeign 日志配置
- 在配置文件中设置日志级别
# 设置某一个服务接口的日志级别
logging.level.[com.wxw.example.springcloudconsumer.controller.IHelloControllerFeign]=DEBUG
- 创建Logger配置类
package com.wxw.example.springcloudconsumer.controller.feignlog;
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignLogConfig {
@Bean
Logger.Level feignLogger(){
return Logger.Level.FULL;
}
}
- 在服务接口中添加配置注解
package com.wxw.example.springcloudconsumer.controller;
import com.wxw.example.springcloudconsumer.controller.feignlog.FeignLogConfig;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(name = "provider-service", configuration = FeignLogConfig.class)
public interface IHelloControllerFeign {
@RequestMapping("/hello")
String hello();
}
替换默认的底层通信
Feign底层默认提供的是URLConnection,可以替换为okHttp。
- 引入okHttp的依赖
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>
- 在配置文件中添加配置
# 关闭httpclient
feign.httpclient.enabled=false
# 启用okhttp
feign.okhttp.enabled=true