基于Feign的远程调用
一.RestTemplate发起远程调用
存在下面的问题:
- 代码可读性差,编程体验不统一
- 参数复杂URL难以维护
二.Feign客户端(声明式)的使用
1.引入依赖
<!--Feign客户端依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.在启动类添加注解@EnableFeignClients
开启Feign的功能
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
3.编写Feign客户端
@FeignClient("userservice")
@Component
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
主要是基于SpringMVC的注解来声明远程调用的信息,比如:
- 服务名称:userservice
- 请求方式:GET
- 请求路径:/user/{id)
- 请求参数:Long id
- 返回值类型:User
4.用Feign客户端代替RestTemplate
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private UserClient userClient;
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
// 2.用Feign远程调用
User user = userClient.findById(order.getUserId());
// 3.封装user到order
order.setUser(user);
// 4.返回
return order;
}
}
三.自定义Feign配置
方式一:配置文件
feign:
client:
config:
default: #这里用default就是全局配置(全局生效),如果是写服务名称,则是针对某个微服务的配置
loggerLevel: Full #日志级别
方式二:bean注入
public class FeignConfig {
@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
四.Feign的性能优化
Feign底层的客户端实现
- URLConnection:默认实现,不支持连接池
- Apache HttpClient:支持连接池
- OKHttp:支持连接池
因此优化Feign的性能主要包括:
- 使用连接池代替默认的URLConnection
- 日志级别,最好用basic或none
1.连接池配置
1)Feign添加HttpClient支持依赖
<!-- httpclient的依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
2)配置连接池
feign:
client:
config:
default: #default全局的配置
loggerLevel: BASIC #日志级别,BASIC就是基本的请求和响应信息
httpclient:
enabled: true #开feign对HttpClient的支持
max-connections: 200 #最大的连接数
max-connections-per-route: 50 #每个路径的最大连接数