分布式解决方案
nacos 配置中心、注册中心
ribbon 负载均衡
openfeign rpc调用
sentinel 流量控制、熔断
gateway api网关
sleuth 调用链监控
seata 分布式事务
nacos简单配置
- 在 common 模块中,导入nacos 相关依赖。这样各个微服务模块都可以使用。
- 配置文件改为 bootstrap.yml 其中只写服务名称、端口、环境、nacos 地址
spring:
profiles:
active: dev # 环境
cloud:
nacos:
discovery:# nacos 注册中心
server-addr: 192.168.2.3:8848
config: // nacos 配置中心
server-addr: 192.168.2.3:8848
file-extension: yaml
namespace: product # 读取配置时所在空间
application:
name: gulimall-product # 服务名称
server:
port: 35200
main函数主启动上,添加服务发现注解@EnableDiscoveryClient
- 在 nacos 网页上添加namespace和每个服务对应的配置信息
注意 Date Id 按照 服务名-环境.yaml 书写
nacos 持久化
- 首先准备好相关数据库。建表语句如下。(踩坑nacos 不支持mysql utf8mb4,所以不要在 my.cnf 中指定这种字符集)
https://blog.csdn.net/samHuangLiang/article/details/104966744
- 修改数据库的隔离级别
SET @@transaction_isolation=‘READ-COMMITTED’;
- 下载 docker 环境 nacos,并启动
docker pull nacos/nacos-server:1.2.1
docker run --env MODE=standalone --name nacosGrain -d -p 8848:8848 nacos/nacos-server:1.2.1
- 进入容器配置 nacos
docker exec -it nacosGrain bash
vi conf/application.properties
修改数据库相关配置
# spring
server.servlet.contextPath=${SERVER_SERVLET_CONTEXTPATH:/nacos}
server.contextPath=/nacos
server.port=${NACOS_SERVER_PORT:8848}
spring.datasource.platform=mysql
nacos.cmdb.dumpTaskInterval=3600
nacos.cmdb.eventTaskInterval=10
nacos.cmdb.labelTaskInterval=300
nacos.cmdb.loadDataAtStart=false
db.num=${MYSQL_DATABASE_NUM:1}
db.url.0=jdbc:mysql://192.168.2.3:23306/gulimall_nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&serverTimezone=Asia/Shanghai
# db.url.1=jdbc:mysql://${MYSQL_SERVICE_HOST}:${MYSQL_SERVICE_PORT:3306}/${MYSQL_SERVICE_DB_NAME}?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=123456
gateway 微服务网关搭建
- 新建 gulimall-gateway 模块,引入 gateway 依赖和 common 依赖
- 主启动加上 @EnableDiscoveryClient
- 配置文件
spring:
application:
name: gulimall-gateway
profiles:
active: dev
cloud:
nacos:
discovery:
server-addr: 192.168.2.13:8848
config:
server-addr: 192.168.2.13:8848
file-extension: yaml
namespace: gateway
- nacos 中配置文件
spring:
cloud:
gateway:
routes:
- id: route_baidu
uri: https://www.baidu.com
predicates:
- Query=url,baidu
- id: route_qq
uri: https://www.qq.com
predicates:
- Query=url,qq
server:
port: 20088
- 测试
踩坑。如果在启动网关时,报错:没有找到数据库配置信息,那么在main函数上加上
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})