一、问题

1、之前的RestTemplate为什么不用了?

之前利用RestTemplate发起远程调用的代码,代码可读性差,编程体验不统一,参数复杂URL难以维护

2、怎么解决?

OpenFeign,Feign是一个声明式的http客户端,官方链接

3、Fegin的使用步骤

1)服务的消费者引入依赖:::tips


org.springframework.cloud
spring-cloud-starter-openfeign
::: 2)添加注解@EnableFeignClients //注解开启Feign

@MapperScan(“cn.itcast.order.mapper”)
@SpringBootApplication
@EnableFeignClients //注解开启Feign
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
} }

3)编写一个Fegin客户端


/*
@author: hanyaning
*
@date: 2022/06/22
*
@description:
__
*/
@FeignClient(“userservice”)
public interface UserFeignClient {
@GetMapping(“/user/{id}”)
User queryById(@PathVariable(“id”) Long id);
}

4)测试

@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RestTemplate restTemplate;

  1. @Autowired<br /> **private **UserFeignClient userFeignClient;<br /> **public **Order queryOrderById(Long orderId) {<br /> // 1.查询订单<br /> Order order = orderMapper.findById(orderId);<br />// //获取user的url地址userservice = localhost:8080<br />// String url = "http://userservice/user/"+order.getUserId();<br />// //根据id获取用户信息<br />// User user = restTemplate.getForObject(url, User.class);<br /> //利用feign发起http请求,查询用户信息<br /> User user = userFeignClient.queryById(order.getUserId());<br /> //把user信息封装到订单中<br /> order.setUser(user);<br /> // 4.返回<br /> **return **order;<br /> }<br />}

4、总结

:::tips 使用Feign的步骤:
① 引入依赖
② 添加@EnableFeignClients注解
③ 编写FeignClient接口
④ 使用FeignClient中定义的方法代替RestTemplate :::