SpringCloud - Feign

发布时间 2023-09-09 10:48:18作者: chuangzhou

Feign 入门

先看 RestTemplate 发起远程调用的代码:

        String url = "http://userservice/user/" + order.getUserId();
        User user = restTemplate.getForObject(url, User.class);

存在以下问题:

  • 代码可读性差,编程体验不统一
  • 参数复杂URL难以维护

Feign 是一个声明式的http 客户端,官方地址:https://github.com/OpenFeign/feign
其作用就是帮助我们优雅的实现http请求的发送,解决上面提到的问题

使用入门:
1.引入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2.启动类开启注解

3.编写客户端

package cn.itcast.order.client;


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")
public interface UserClient {
  
    /*
    主要是使用SpringMVC的注解来声明远程调用:
      1.服务名称:userservice
      2.请求方式:Get
      3.请求路径:/user/{id}
      4.请求参数: Long id
      5.返回值类型:User
    */
    @GetMapping("/user/{id}")
    User fingById(@PathVariable("id") Long id);
}

4.修改order-service

@Autowired
private UserClient userClient;

public Order queryOrderById(Long orderId) {
    // 1.查询订单
    Order order = orderMapper.findById(orderId);
    //2.查询用户信息
    User user = userClient.fingById(order.getUserId());
    order.setUser(user);
    // 3.返回
    return order;
}