1:首先了解工作流程,创建两个数据库,一个order,一个user,当然order中有对应user信息。这里呢既然使用微服务思想,那就不能将他们两个放到一个库中,因此这里不能调用对方得Service层(都不在一个数据库下面,也就没有办法去调用了),那么就拿不到数据,应该怎么办呢?
首先将对方需要得接口暴露出去(这里可以使用Restful风格),然后使用方将记住该接口得url,这样就可以拿到想要得数据了。具体操作如下:
2:在Spring容器中注入 RestTemplate(在启动类下面)
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
3:在service层调用对方暴露出来得restful风格得接口
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
//利用RestTemplate发送HTTP请求,查询用户
//2.1 url路径(这里指的是要发送请求得路径,记得将用户ID加在后面)
String url = "http://localhost:8081/user/"+order.getUserId();
//2.2 发送HTTP请求 得到远程对象
User user = restTemplate.getForObject(url, User.class);
//3:封装user到order中
order.setUser(user);
// 4.返回
return order;
}
}
4:结果(这样就可以拿到对应得结果了)