// 1. 添加依赖
// Spring Cloud 2020.x 之后需要额外引入 loadbalancer
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
// 2. 启用Feign
@SpringBootApplication
@EnableFeignClients
public class Application { ... }
// 3. 定义接口
@FeignClient(name = "user-service")
public interface UserClient {
@GetMapping("/users/{id}")
User getUser(@PathVariable Long id);
}
// 4. 注入使用
@RestController
public class UserController {
@Autowired
private UserClient userClient;
@GetMapping("/proxy/users/{id}")
public User getUser(@PathVariable Long id) {
return userClient.getUser(id);
}
}
# application.yml
openfeign:
client:
config:
default: # 全局默认配置
connectTimeout: 5000 # 连接超时(ms)
readTimeout: 30000 # 读取超时(ms)
user-service: # 针对单个服务进行配置
connectTimeout: 2000
readTimeout: 5000
@Configuration
public class FeignConfig {
// 默认实现不进行重试
@Bean
public Retryer feignRetryer() {
// 参数:间隔时间(ms),最大间隔时间(ms),最大尝试次数(含第一次)
return new Retryer.Default(100, 1000, 3);
}
// 开启feign的日志
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL; // 设置日志级别
}
}
# application.yml
openfeign:
client:
config:
default: # 全局默认配置
connectTimeout: 10000 # 连接超时(ms)
readTimeout: 20000 # 读取超时(ms)
httpclient:
hc5: # 使用http5进行优化
enabled: true
compression:
request:
enabled: true
mime-types: text/xml,application/xml,application/json #触发压缩的数据类型
min-request-size: 2048 #最小处罚压缩大小
response:
enabled: true
引入依赖
<!-- HttpClient5 核心依赖 -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.3</version>
</dependency>
<!-- Feign对HttpClient5的适配器 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-hc5</artifactId>
<version>13.1</version>
</dependency>