@[TOC]
1 Feign简介
- Feign是一个声明式的http客户端,作用就是帮助我们优雅的实现http请求的发送,解决RestTemplate的问题。
1.1 RestTemplate发送get请求
RestTemplateBuilder builder = new RestTemplateBuilder(); RestTemplate restTemplate = builder.build(); String url = "https://v2.alapi.cn/api/new/wbtop?num=100&token=4DZmP3cZ930V2z7X"; String forObject = restTemplate.getForObject(url, String.class); JSONObject jsonObject = JSONObject.parseObject(forObject); Object data = jsonObject.get("data"); List<WeiBoHotVO> dataJson = JSONObject.parseArray(data.toString(), WeiBoHotVO.class);
1.2 RestTemplate发送post请求
- 发送参数
String url = "*****"; MultiValueMap map = new LinkedMultiValueMap(); map.add("username", username); map.add("password", password); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, map, String.class); return responseEntity.getBody();
- 发送json
String url = "*****"; Member member = new Member(); member.setEmail(username); member.setPassword(password); ResponseEntity<Member> memberResponseEntity = restTemplate.postForEntity(url, member, Member.class); return memberResponseEntity.getBody();
1.3 RestTemplate发送通用请求
String url = "*****"; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); //设置访问参数 HashMap<String, Object> params = new HashMap<>(); params.put("username", username); //设置访问的Entity HttpEntity entity = new HttpEntity<>(params, headers); ResponseEntity<String> result; try { //发起一个POST请求 result = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); JSONObject data = JSONObject.parseObject(result.getBody()).getJSONObject("data"); return data.getString("id"); } catch (Exception e) { }
2 Feign客户端的使用
2.1 引入依赖
<!-- SpringCloud Openfeign --> <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
- 方式二: java代码
自定义日志
@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 配置 feign: sentinel: enabled: true okhttp: enabled: true httpclient: enabled: false client: config: default: connectTimeout: 10000 readTimeout: 10000 compression: request: enabled: true response: enabled: true
日志级别,最好用basic或none