做全网vip电影网站违法吗,国际贸易进出口,怎么推广app,网站开发需要经历哪些主要阶段为什么要进行微服务拆分#xff1f;
在平常的商城项目中#xff0c;我们一般的项目结构模块都是将各种业务放在同一个项目文件夹#xff0c;比如像#xff1a; 用户#xff0c;购物车#xff0c;商品#xff0c;订单#xff0c;支付等业务都是放在一起#xff0c;这样…为什么要进行微服务拆分
在平常的商城项目中我们一般的项目结构模块都是将各种业务放在同一个项目文件夹比如像 用户购物车商品订单支付等业务都是放在一起这样很容易一个文件改动造成多个文件也要变动而且在团队项目中也不容易维护所以可以进行微服务拆分来解决这个问题。
怎么拆分 从拆分目标来说要做到 高内聚每个微服务的职责要尽量单一包含的业务相互关联度高、完整度高。低耦合每个微服务的功能要相对独立尽量减少对其它微服务的依赖。 从拆分方式来说一般包含两种方式 纵向拆分按照业务模块来拆分横向拆分抽取公共服务提高复用性 对于hmall商城项目它分为5大模块
用户模块商品模块购物车模块订单模块支付模块
我这里采用的是横向拆分把它们公共的服务提取出来放在hm-api里面
比如在购物车模块里面它使用到了商品模块里面的服务 那么就可以把购物车模块里面用到的商品模块里面的服务抽取出来。
实现微服务拆分
前提
IDEA2021以上版本JDK11VMware Workstation ProMobaXterm
会使用docker涉及到服务的远程调用这里使用的是nacos注册中心
项目架构 hm-api:抽取出来的公共服务 用户业务
新建项目 从原本的单体商城项目中把用户模块的内容复制过来如图 这里还有很重要的是配置yaml文件
application.yaml application-dev.yaml application-local.yaml 在运行前先配置一下UserApplication 连接上虚拟机开启MySQL和nacos 一些命令
# 设置开机自启systemctl enable docker#查看docker ps#启动数据库docker start mysql#访问nacosdocker log -f nacos
运行成功 同理剩下的4个业务也是这样拆分其实公共服务就是把各个业务交织的部分抽取出来这样就只需要在hm-api里面去调用就可以
并且pom.xml里面要引入这个公共服务api
!-- hm-api--dependencygroupIdcom.heima/groupIdartifactIdhm-api/artifactIdversion1.0.0/version/dependency
hm-api
项目结构 client
package com.hmall.api.client;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;import java.util.List;
import java.util.Set;FeignClient(cart-service)
public interface CartClient {DeleteMapping(/carts)void deleteCartItemByIds(RequestParam(ids) SetLong ids);
}package com.hmall.api.client;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestParam;import java.util.List;
import java.util.Set;FeignClient(cart-service)
public interface CartClient {DeleteMapping(/carts)void deleteCartItemByIds(RequestParam(ids) SetLong ids);
}package com.hmall.api.client;import io.swagger.annotations.ApiImplicitParam;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
FeignClient(trade-service)
public interface TradeClient {ApiImplicitParam(name orderId, value 订单id, paramType path)PutMapping(/orders/{orderId})void markOrderPaySuccess(PathVariable(orderId) Long orderId);
}package com.hmall.api.client;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
FeignClient(user-service)
public interface UserClient {PutMapping(/users/money/deduct)public void deductMoney(RequestParam(pw) String pw, RequestParam(amount) Integer amount);
}总结
微服务架构首先是服务化就是将单体架构中的功能模块从单体应用中拆分出来独立部署为多个服务。同时要满足下面的一些特点 单一职责一个微服务负责一部分业务功能并且其核心数据不依赖于其它模块。 团队自治每个微服务都有自己独立的开发、测试、发布、运维人员团队人员规模不超过10人 服务自治每个微服务都独立打包部署访问自己独立的数据库。并且要做好服务隔离避免对其它服务产生影响