Feign
# 引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
1
2
3
4
2
3
4
# 启动类中添加注解
@EnableFeignClients
@SpringBootApplication
public class Application{
...
}
1
2
3
4
5
2
3
4
5
# 编写Feign客户端
在order-service中新建接口;
基于SpringMVC的注解来声明远程调用的信息,比如:
- 服务名称:userservice
- 请求方式:GET
- 请求路径:/user/{id}
- 请求参数:Long id
- 返回值类型:User
@FeignClient("userservice") public interface UserClient { @GetMapping("/user/{id}") User findById(@PathVariable("id") Long id); }
1
2
3
4
5order-service中;
@Autowired private UserClient userClient; public Order queryOrderById(Long orderId){ Order order = orderMapper.findById(orderId); User user = userClient.findById(order.getUserId()); order.setUser(user); return order; }
1
2
3
4
5
6
7
8
9