Feign
Feign是一个声明式的http客户端,官方地址:https://github.com/OpenFeign/feign
1.使用
1.引入依赖
<!-- Feign客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
@EnableFeignClients //注解开启
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
3.创建client文件,编写接口类
/**
* @Date 2022/10/30 19:17
* @Author 郜宇博
*/
@FeignClient("userservice")
public interface UserClient {
/**
* @param id userid
* @return User对象
*
*/
@GetMapping("user/{id}")
User findById(@PathVariable("id") Long id);
}
4.使用
@GetMapping("{orderId}")
public Order queryOrderByUserId(@PathVariable("orderId") Long orderId) {
// 根据id查询订单并返回
Order order = orderService.queryOrderById(orderId);
//调用接口==================
User user = userClient.queryById(order.getUserId());
//调用接口结束=====================
order.setUser(user);
return order;
}
并且feign已经集成了ribbon
2.性能优化
1.HttpClient支持
2.连接池
3.日志级别尽量用basic
feign底层的连接是没有连接池的,需要更换httpclient
<!-- Feign-http-->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
连接池配置
feign:
httpclient:
enabled: true # 支持httpclient
3.实践使用
1.创建feign-api模块整合请求
2.引入依赖
<!-- Feign客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
3.编写client接口和实体类
/**
* @Date 2022/10/30 19:17
* @Author 郜宇博
*/
@FeignClient("userservice")
public interface UserClient {
/**
* @param id userid
* @return User对象
* 11
*/
@GetMapping("user/{id}")
User findById(@PathVariable("id") Long id);
}
4.在消费者pom文件中引入编写的feign-api工程
<!-- feign-api-->
<dependency>
<groupId>cn.itcast.demo</groupId>
<artifactId>feign-api</artifactId>
<version>1.0</version>
</dependency>
5.使用前注入client类
由于在其他工程中,因此无法直接注入,需要在启动类的注解中加入Client类
@Autowired
private UserClient userClient;
启动类中
6.使用
//调用接口==================
User user = userClient.queryById(order.getUserId());
//调用接口结束=====================