微服务学习笔记--(服务拆分及远程调用)

服务拆分及远程调用

  • 服务拆分
  • 服务间调用

服务拆分注意事项

1.不同微服务,不要重复开发相同的业务
2.微服务数据独立,不要访问其它微服务的数据库
3.微服务可以将自己的业务暴露为接口,供其它微服务调用

小结:

1.微服务需要根据业务模块拆分,做到单一职责,不要重复开发相同的业务
2.微服务可以将自己的业务暴露为接口,供其它微服务调用
3.不同微服务都应该有自己独立的数据库


案例:根据订单id查询订单功能

需求:根据订单id查询订单的同时,把订单所属的用户信息一起返回

步骤

1)注册RestTemplate

在order-service的OrderAplication中注册RestTemplate

@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;
	}
}

小结:

微服务调用方式

  • 基于RestTemplate发起的http请求实现远程调用
  • http请求做远程调用是与语言无关的调用,只要知道对方的ip、端口、接口路径、请求参数即可。

猜你喜欢

转载自blog.csdn.net/weixin_42594143/article/details/130403602