微服务拆分注意事项
1、微服务需要根据业务模块拆分,做到单一职责,不要重复开发相同业务。
2、微服务数据独立,不要访问其他微服务的数据库。(每个微服务都有自己的数据库)
3、微服务可以将自己的业务暴露为接口,供其他微服务调用。
微服务远程调用
1、基于 RestTemplate发起的http请求实现远程调用。
2、http请求做远程调用是与语言无关的调用,只要知道对方的ip、端口、接口路径、请求参数即可。
RestTemplate发起的http请求实现远程调用--使用
@SpringBootApplication
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
/**
* 创建RestTemplate并注入Spring容器
*/
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
/**
* @author 邓林妹
* @description TODO
* @date 2022/12/10
*/
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RestTemplate restTemplate;
@Override
public Order queryOrderByOrderId(Long orderId) {
//1、查询订单
Order order = orderMapper.queryOrderByOrderId(orderId);
//2、利用RestTemplate发起http请求,查询用户
//3、用户微服务提供的对外接口地址
Long userId = order.getUserId();
String url="http://localhost:8081/user/"+userId;
//4、发送http请求,实现远程调用
User user = restTemplate.getForObject(url, User.class);
order.setUser(user);
return order;
}
}