一、Fegin替代RestTemplate
RestTemplate:代码可读性差,编程体验不统一,参数复杂URL难以维护。
Feign:是一个声明式的http客户端,官方地址: https://github.com/OpenFeign/feign,其作用就是帮助我们优雅的实现http请求的发送,解决上面提到的问题。
使用Feign步骤如下:
1、引入依赖
<!--Feign的客户端依赖--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
2、在orderservice启动类添加注解开启Feign的功能
3、编写Feign客户端
package cn.itcast.order.clients;import cn.itcast.order.pojo.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;@FeignClient("userservice") //发送http请求时需要知道服务名称,在此指定
public interface UserClient {@GetMapping("/user/{id}")User findById(@PathVariable("id") Long id);
}
修改orderService:
package cn.itcast.order.service;import cn.itcast.order.clients.UserClient;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import cn.itcast.order.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;@Service
public class OrderService {@Autowiredprivate OrderMapper orderMapper;@Autowiredprivate UserClient userClient;public Order queryOrderById(Long orderId) {// 1.查询订单Order order = orderMapper.findById(orderId);//2、利用Feign远程调用User user = userClient.findById(order.getUserId());//3 封装user到orderorder.setUser(user);// 4.返回return order;}
/* @Autowiredprivate RestTemplate restTemplate;public Order queryOrderById(Long orderId) {// 1.查询订单Order order = orderMapper.findById(orderId);//2、利用RestTemplate发送http请求,查询用户//2.1 url路径String url = "http://userservice/user/" + order.getUserId();//2.2 发起http请求,实现远程调用(原本返回的是json,告诉它我们要User对象类型)User user = restTemplate.getForObject(url, User.class);//3 封装user到orderorder.setUser(user);// 4.返回return order;}*/
}
二、自定义配置
全局生效:
三、Feign性能优化—连接池配置
Fegin添加HttpClient依赖
<!--引入HttpClient依赖--><dependency><groupId>io.github.openfeign</groupId><artifactId>feign-httpclient</artifactId></dependency>
feign:httpclient:enabled: true # 支持HttpClient的开关max-connections: 200 #最大连接数max-connections-per-route: 50 #单个路径的最大连接数