拆分原则
什么时候拆分
- 大多数小型项目: 一般是先采用单体架构,随着用户规模扩大、业务复杂后再逐渐拆分为微服务架构(前易后难)。
- 确定的大型项目: 资金充足,目标明确,可以直接选择微服务架构,避免后续拆分的麻烦(前难后易)。
怎么拆分
拆分目标:
- 高内聚:每个微服务的职责要尽量单一,包含的业务相互关联度高、完整度高。
- 低耦合:每个微服务的功能要相对独立,尽量减少对其它微服务的依赖,或者依赖接口的稳定性要强。
拆分方式:
- 纵向拆分:按照业务模块来拆分。
- 横向拆分:抽取公共服务,提高复用性。
当然,由于黑马商城并不是一个完整的项目,其中的短信发送、风控管理并没有实现,这里就不再考虑了。而其它的业务按照纵向拆分,可以分为以下几个微服务:
- 用户服务
- 商品服务
- 订单服务
- 购物车服务
- 支付服务
拆分服务

工程结构有两种:
- 独立Project
- Maven聚合(使用最多)
拆分操作

新建一个module,命名为item-service
- 由于我已经新建过了这个module,所以会显示存在,这是正常的。
- 将hm-service中的controller domain mapper service还有resource中的配置文件拷贝到item-service中,注意只需要拷贝跟item-service中的文件就行,如果关联其他文件,那就一并拷贝下来。注意:如果import包爆红的话,那可能是正常的。只需要把包删了,重新导入一下就行。
application.yaml:
c
server:
port: 8081
spring:
application:
name: item-service
profiles:
active: dev
datasource:
url: jdbc:mysql://${hm.db.host}:3306/hm-item?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: ${hm.db.pw}
mybatis-plus:
configuration:
default-enum-type-handler: com.baomidou.mybatisplus.core.handlers.MybatisEnumTypeHandler
global-config:
db-config:
update-strategy: not_null
id-type: auto
logging:
level:
com.hmall: debug
pattern:
dateformat: HH:mm:ss:SSS
file:
path: "logs/${spring.application.name}"
knife4j:
enable: true
openapi:
title: 黑马商城接口文档
description: "黑马商城服务接口文档"
email: [email protected]
concat: 虎哥
url: https://www.itcast.cn
version: v1.0.0
group:
default:
group-name: default
api-rule: package
api-rule-resources:
- com.hmall.item.controller
hm:
jwt:
location: classpath:hmall.jks
alias: hmall
password: hmall123
tokenTTL: 30m
auth:
excludePaths:
- /search/**
- /users/login
- /items/**
- /hi
# keytool -genkeypair -alias hmall -keyalg RSA -keypass hmall123 -keystore hmall.jks -storepass hmall123
application-dev.yaml
c
hm:
db:
host: mysql
pw: 123
application-local.yaml
c
hm:
db:
host: 10.105.2.124 # 修改为你自己的虚拟机IP地址
pw: 123 # 修改为docker中的MySQL密码
- 操作虚拟机中的数据库
参考这两篇博客:
如何在docker中的mysql容器内执行命令与执行SQL文件
先把要执行的sql文件导入/root根目录下,然后进行以下操作:
将idea与虚拟机docker中的mysql数据库连接
我的密码是123(mark一下,我怕我忘了) - 测试一下