注册RestTemplate:在order-service的模块中注册RestTemplate
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
在查询订单时发送http请求用户信息
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
Order order = orderMapper.findById(orderId);
String url ="http://localhost:8081/user/"+order.getUserId();
User user = restTemplate.getForObject(url, User.class);
order.setUser(user);
return order;
}
}
这样就可以在查询订单消息的同时查询用户信息,解决了微服务远程调用
微服务调用方式:
- 基于RestTemplate发起的http请求实现远程
- http请求做远程调用是与语言无关的调用,只要知道对方的ip,端口,接口路径,请求参数即可。
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LCqBCN2P-1671717226169)(C:\Users\20745\AppData\Roaming\Typora\typora-user-images\image-20221221231503391.png)]](https://img-blog.csdnimg.cn/173fdb09772d47a8a31a9e5555b988d0.png)