微服务-服务拆分

文章目录

服务拆分及注意事项

每个服务有独立的数据库,订单模块需要查询用户信息时,通过调用用户模块的接口,自身的数据库并没有用户信息。

服务拆分案例

案例结构

案例有2个微服务,order-service微服务对应的表为cloud-order,user-service微服务对应的表为cloud-user。在实际生产部署时,这两个表会被放在不同的数据库中,没有办法做关联查询。

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

案例代码分析

  1. 配置类
java 复制代码
/**
 * @SpringBootConfiguration继承自@Configuration,
 * 二者功能也一致,标注当前类是配置类,并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到spring容器中
 */
@SpringBootConfiguration
public class WebConfiguration {

    @Bean //相当于@Controller,@Service等
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
  1. OrderService类
java 复制代码
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    // 获取restTemplate对象
    @Autowired
    private RestTemplate restTemplate;

    public Order queryOrderById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.findById(orderId);
        // 2.定义url
        String url = "http://localhost:8081/user/"+order.getUserId();
        // 3.发送http请求
        User user = restTemplate.getForObject(url, User.class);
        // 4.封装user
        order.setUser(user);
        // 5.返回
        return order;
    }
}
  1. 测试
相关推荐
xcl092539 分钟前
北京24小时自助健身房系统软件开发实战:从架构到部署全流程指南
java·spring boot·架构
一 乐2 小时前
动漫书销售商城|基于springboot + vue动漫书销售商城(源码+数据库+文档)
java·数据库·vue.js·spring boot·毕业设计
卓怡学长3 小时前
w214基于jsp知道特产网
java·intellij-idea
步行cgn3 小时前
Spring 注解使用详解
java·spring
一条小小yu3 小时前
Spring IoC的理解
java·后端·spring
落魄实习生3 小时前
Agent Scope Java 2.x 系列【7】工具使用
java·开发语言·ai
旺仔学长 哈哈4 小时前
springboot钓鱼爱好者交流平台APP设计与实现
java·spring boot·mysql·充电桩管理系统
自强的小白5 小时前
核心功能(Service接口)
java·mybatis
乌暮6 小时前
深入理解 Java 泛型:把「万能盒子」用对、用稳
java·开发语言·后端·学习