Service splitting and remote calling
- service split
- call between services
Considerations for Service Splitting
1. Different microservices, do not repeatedly develop the same business
2. Microservice data is independent, do not access the database of other microservices
3. Microservices can expose their own business as an interface for other microservices to call
summary:
1. Microservices need to be split according to business modules to achieve a single responsibility, and do not repeatedly develop the same business.
2. Microservices can expose their own business as interfaces for other microservices to call.
3. Different microservices should have their own independence database
Case: query order function based on order id
Requirement: While querying the order according to the order id, return the user information to which the order belongs
step
1) Register RestTemplate
Register RestTemplate in OrderAplication of order-service
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
OrderService.java
@Service
public class OrderService {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RestTemplate restTemplate;
public Order queryOrderById(Long orderId) {
//1.查询订单
Order order = orderMapper.findById(orderId);
//2.利用RestTemplate发起http请求,查询用户
//2.1.url路径
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;
}
}
summary:
Microservice calling method
- Realize remote call based on http request initiated by RestTemplate
- Remote calls made by http requests are language-independent calls, as long as you know the other party's ip, port, interface path, and request parameters.