单体项目拆分成微服务项目—远程调用问题

发布时间:2026/7/29 3:43:00

单体项目拆分成微服务项目—远程调用问题 1. 什么时候拆分微服务?● 初创型公司或项目尽量采用单体项目,快速试错。随着项目发展到达一定规模再做拆分2. 如何拆分微服务?● 目标:高内聚、低耦合。● 方式:纵向拆分、横向拆分3. 拆分后碰到的第一个问题是什么,如何解决?● 拆分后,某些数据在不同服务,无法直接调用本地方法查询数据● 利用RestTemplate发送Http请求,实现远程调用4. 远程调用方法5. 举个例子private void handleCartItems(ListCartVO vos) { // 1.获取商品id SetLong itemIds vos.stream().map(CartVO::getItemId).collect(Collectors.toSet()); // 2.查询商品 // ListItemDTO items itemService.queryItemByIds(itemIds); // if (CollUtils.isEmpty(items)) { // throw new BadRequestException(购物车中商品不存在); // } // 2.1.利用RestTemplate发起http请求得到http的响应 ResponseEntityListItemDTO response restTemplate.exchange( http://localhost:8081/items?ids{ids}, HttpMethod.GET, null, new ParameterizedTypeReferenceListItemDTO() { }, Map.of(ids, CollUtil.join(itemIds, ,)) ); // 2.2.解析响应 if (!response.getStatusCode().is2xxSuccessful()) { // 查询失败直接结束 return; } ListItemDTO items response.getBody(); if (CollUtils.isEmpty(items)) { return; } // 3.转为 id 到 item的map MapLong, ItemDTO itemMap items.stream().collect(Collectors.toMap(ItemDTO::getId, Function.identity())); // 4.写入vo for (CartVO v : vos) { ItemDTO item itemMap.get(v.getItemId()); if (item null) { continue; } v.setNewPrice(item.getPrice()); v.setStatus(item.getStatus()); v.setStock(item.getStock()); } }

相关新闻