1 Feign简介
- Feign是一个声明式的http客户端,作用就是帮助我们优雅的实现http请求的发送,解决上面提到的问题。
2 Feign客户端的使用
2.1 引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.2 第二步添加注解@EnableFeignClients
@EnableFeignClients
public @interface EnableMyFeignClients{
}
2.3 编写Feign客户端
声明:服务名称、请求方式、请求路径、请求参数、返回值类型
@FeignClient("userservice")
public interface UserClient{
@GetMapping("/user/{id}")
User findById(@PathVariable("id" Long id));
}
3 Feign的自定义配置
- 日志级别NONE、BASIC、HEADERS、FULL
- 方式一:配置文件
feign:
client:
config:
default:
loggerLevel: BASIC
@Component
public class RemoteUserFallbackFactory implements FallbackFactory<RemoteUserService>
{
private static final Logger log = LoggerFactory.getLogger(RemoteUserFallbackFactory.class);
@Override
public RemoteUserService create(Throwable throwable)
{
log.error("用户服务调用失败:{}", throwable.getMessage());
return new RemoteUserService()
{
@Override
public R<LoginUser> getUserInfo(String username, String source)
{
return R.fail("获取用户失败:" + throwable.getMessage());
}
@Override
public R<Boolean> registerUserInfo(SysUser sysUser, String source)
{
return R.fail("注册用户失败:" + throwable.getMessage());
}
};
}
}
@FeignClient(contextId = "remoteUserService", value = ServiceNameConstants.SYSTEM_SERVICE, fallbackFactory = RemoteUserFallbackFactory.class)
4 Feign的性能优化
Feign底层的客户端实现:
- URLConnection:默认实现,不支持连接池
- Apache HttpClient:支持连接池
- OKHttp:支持连接池
性能优化主要包括: - 使用连接池代替默认的URLConnection
feign:
sentinel:
enabled: true
okhttp:
enabled: true
httpclient:
enabled: false
client:
config:
default:
connectTimeout: 10000
readTimeout: 10000
compression:
request:
enabled: true
response:
enabled: true
|