OpenFeign是一种声明式、模板化的HTTP客户端(仅在Application Client中使用)(称OpenFeign作用:声明式服务调用)。声明式调用是指,就像调用本地方法一样调用远程方法,无需感知操作远程http请求。OpenFeign替换RestTemplate。
(1)导入依赖
org.springframework.boot
<artifactId>spring-boot-starter-parent
2.3.12.RELEASE
org.springframework.cloud
spring-cloud-dependencies
Hoxton.SR12
pom
import
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.cloud
spring-cloud-starter-openfeign
(2)在启动类上添加扫描注解
- /**
- * EnableFeignClients - 开启Openfeign技术。让spring cloud扫描Openfeign相关注解,
- * 生成动态代理实现对象。
- * 可选属性 basePackages = {"feign接口所在包1", "feign接口所在包2"}
- * 默认扫描当前类型所在包,及所有子孙包。
- */
- @SpringBootApplication
- @EnableEurekaClient
- @EnableFeignClients(basePackages = {"com.bjsxt.feign"})
- public class OpenFeignAppClientApp {
- public static void main(String[] args) {
- SpringApplication.run(OpenFeignAppClientApp.class, args);
- }
- }
(3)编写本地接口
- /**
- * 定义接口,基于注解,实现声明式远程服务调用。
- * 技术是OpenFeign。
- * 需要确定的事情:
- * 1. 访问的远程服务名称是什么。
- * 2. 访问的远程服务具体地址是什么。
- * 3. 访问的远程服务请求方式是什么。
- * 4. 访问的远程服务,参数是什么。
- * 5. 访问的远程服务,返回结果类型是什么。
- *
- * FeignClient - 代表当前的接口是一个OpenFeign客户端,要访问远程的服务。
- * 具体的实现类对象,由spring cloud动态生成代理对象来实现。
- * 必要属性: value - 要访问的远程服务命名是什么。
- */
- @FeignClient("application-service")
- public interface AppServiceOpenfeignClient {
- /**
- * 定义方法。使用SpringMVC注解+方法定义,实现远程服务访问规则定义。
- * 建议写法: 找到要访问的控制器。复制对应的方法签名即可。
- *
- * GetMapping - 约束了请求方式
- * 注解属性value - 约束了请求的具体地址
- * 方法返回值 - 约束了远程服务返回结果类型
- * 方法参数表 - 约束了远程服务的请求参数
- */
- @GetMapping("/getNoParams")
- public String getNoParams();
-
- /**
- * post请求,无参数
- * @return
- */
- @PostMapping("/postNoParams")
- public String postNoParams();
- }
(4)本地接口注意事项
形参需要添加对应注解如@RequestParam,@RequestBody,@PathVariable等。
(1)配置OpenFeign请求-应答的GZIP压缩
# 配置openfeign请求和应答的gzip压缩处理
feign:
compression:
request:
enabled: true # 开启请求压缩处理。默认false
min-request-size: 128 # 请求容量多少,开始压缩。默认2048字节
mime-types: text/html, text/xml, text/plain, text/css, application/json # 请求头content type是什么,做压缩处理
response:
enabled: true # 开启响应压缩处理。默认false
(2)Tomcat服务器GZIP优化配置
server:
compression:
enabled: true # 是否开启响应压缩处理。默认false
mime-types: text/html, text/xml, text/plain, text/css, text/javascript, application/javascript, application/json, application/xml # 响应content type什么类型,做压缩处理。
min-response-size: 128 # 响应容量多大,做压缩处理。 默认2048字节