10.中间件安装(Nacos、Sentinel、Seata、Redis、RabbitMQ)

一、nacos安装

官网:https://nacos.io/zh-cn/docs/v2/quickstart/quick-start-kubernetes.html

1.创建配置字典(可以创建一个单节点模式获取配置文件)


cluster.conf先设置为空

application.properties(更改了数据库)

# spring
server.servlet.contextPath=${SERVER_SERVLET_CONTEXTPATH:/nacos}
server.contextPath=/nacos
server.port=${NACOS_APPLICATION_PORT:8848}
server.tomcat.accesslog.max-days=30
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i %{Request-Source}i
server.tomcat.accesslog.enabled=${TOMCAT_ACCESSLOG_ENABLED:false}
# default current work dir
server.tomcat.basedir=file:.
#*************** Config Module Related Configurations ***************#
### Deprecated configuration property, it is recommended to use `spring.sql.init.platform` replaced.
#spring.datasource.platform=${SPRING_DATASOURCE_PLATFORM:}
spring.sql.init.platform=${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://${MYSQL_SERVICE_HOST:192.168.192.133}:${MYSQL_SERVICE_PORT:32444}/${MYSQL_SERVICE_DB_NAME:nacos}?${MYSQL_SERVICE_DB_PARAM:characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useSSL=false}
db.user.0=${MYSQL_SERVICE_USER:root}
db.password.0=${MYSQL_SERVICE_PASSWORD:123456}
### The auth system to use, currently only 'nacos' and 'ldap' is supported:
nacos.core.auth.system.type=${NACOS_AUTH_SYSTEM_TYPE:nacos}
### worked when nacos.core.auth.system.type=nacos
### The token expiration in seconds:
nacos.core.auth.plugin.nacos.token.expire.seconds=${NACOS_AUTH_TOKEN_EXPIRE_SECONDS:18000}
### The default token:
nacos.core.auth.plugin.nacos.token.secret.key=${NACOS_AUTH_TOKEN:SecretKey012345678901234567890123456789012345678901234567890123456789}
### Turn on/off caching of auth information. By turning on this switch, the update of auth information would have a 15 seconds delay.
nacos.core.auth.caching.enabled=${NACOS_AUTH_CACHE_ENABLE:false}
nacos.core.auth.enable.userAgentAuthWhite=${NACOS_AUTH_USER_AGENT_AUTH_WHITE_ENABLE:false}
nacos.core.auth.server.identity.key=${NACOS_AUTH_IDENTITY_KEY:serverIdentity}
nacos.core.auth.server.identity.value=${NACOS_AUTH_IDENTITY_VALUE:security}
## spring security config
### turn off security
nacos.security.ignore.urls=${NACOS_SECURITY_IGNORE_URLS:/,/error,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/v1/auth/**,/v1/console/health/**,/actuator/**,/v1/console/server/**}
# metrics for elastic search
management.metrics.export.elastic.enabled=false
management.metrics.export.influx.enabled=false
nacos.naming.distro.taskDispatchThreadCount=10
nacos.naming.distro.taskDispatchPeriod=200
nacos.naming.distro.batchSyncKeyCount=1000
nacos.naming.distro.initDataRatio=0.9
nacos.naming.distro.syncRetryDelay=5000
nacos.naming.data.warmup=true

2.创建有状态服务


填写名称和版本


镜像,容器名称,端口设置


设置存储方式为msyql,集群支持IP还是域名模式


注:PREFER_HOST_MODE=hostname这个值非常重要

时间同步


挂载两个子路径字典



3.获取容器域名

点击服务--》点击刚才创建的服务--》进入容器--》ping DNS



fm-nacos-版本-容器多个的话这个会增加.fm-nacos.fanmaogo.svc.cluster.local

fm-nacos-0-0.fm-nacos.fanmaogo.svc.cluster.local

4.修改集群域名


5.启动多个容器看一下集群效果


6.创建外部可访问的服务

选择指定工作负载


选择虚拟IP地址


选择NodePort


修改yaml


让9848的nodePort大于8848的nodePort,大于值为:1000,不然程序连接报错


注:如果是集群模式只启动一个nacos,程序没有报错但是服务注册不上,需要启动两个nacos等服务注册上在停掉一个nacos即可。

二、Sentinel(控制保存持久化到Nacos)

1.下载对应版本源码(1.8.5和1.8.6通用)

https://github.com/alibaba/Sentinel/releases

2.IDEA导入

3.打开sentinel-dashboard模块下的pom文件,把nacos的test作用域注释掉

4.将 \sentinel-dashboard\src\test\java\com\alibaba\csp\sentinel\dashboard\rule\nacos 文件夹复制到 \sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\rule 下面

FlowRuleNacosProvider.java:从Nacos配置中心动态获取流控规则

FlowRuleNacosPublisher.java:上传动态获取流控规则到Nacos配置中心

NacosConfig.java:nacos配置

NacosConfigUtils.java:流控规则相关配置,比如GROUP_ID 流控规则的后缀FLOW_DATA_ID_POSTFIX

5.在 \sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\rule 目录下创建配置类“NacosProperties.java”

package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @auth LRY
 * @date 2023/3/16
 */
@Component
@ConfigurationProperties(prefix = "sentinel.nacos")
public class NacosProperties {
    /**
     * nacos地址
     */
    private String serverAddr;
    /**
     * nacos命名空间
     */
    private String namespace;
    private String username;
    private String password;


    public String getServerAddr() {
        return serverAddr;
    }

    public void setServerAddr(String serverAddr) {
        this.serverAddr = serverAddr;
    }

    public String getNamespace() {
        return namespace;
    }

    public void setNamespace(String namespace) {
        this.namespace = namespace;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

6.配置文件添加对应配置

#nacos配置
sentinel.nacos.serverAddr=192.168.192.136:30001
sentinel.nacos.namespace=fanmao-dev
sentinel.nacos.username=nacos
sentinel.nacos.password=nacos

7.修改“NacosConfig.java”

/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.*;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Properties;

/**
 * @author Eric Zhao
 * @since 1.4.0
 */
@Configuration
public class NacosConfig {

    //注入nacos配置文件
    @Autowired
    private NacosProperties nacosProperties;

    //===================流控
    @Bean
    public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {
        return JSON::toJSONString;
    }

    @Bean
    public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {
        return s -> JSON.parseArray(s, FlowRuleEntity.class);
    }


    @Bean
    public ConfigService nacosConfigService() throws Exception {
        //修改前
        //return ConfigFactory.createConfigService("localhost");
        //修改后
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, nacosProperties.getServerAddr());
        properties.put(PropertyKeyConst.NAMESPACE, nacosProperties.getNamespace());
        properties.put(PropertyKeyConst.USERNAME, nacosProperties.getUsername());
        properties.put(PropertyKeyConst.PASSWORD, nacosProperties.getPassword());
        return ConfigFactory.createConfigService(properties);
    }
}

8.修改RequestMapping

FlowControllerV1修改前面添加一个/old/

FlowControllerV2修改成FlowControllerV1

9.修改Provider和Publisher

    @Autowired
    @Qualifier("flowRuleNacosProvider")
    private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
    @Autowired
    @Qualifier("flowRuleNacosPublisher")
    private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;

10.上面的流控规则修改完成了,接下来修改熔断规则

把流控的复制出来两份修改成熔断的

修改圈红的部分

DEGRADE_DATA_ID_POSTFIX:这个是自己定义的Nacos配置文件名称

NacosConfig.java 里面添加两个转换器

复制一份重命名

修改两个文件的RequestMapping

将左边的内容替换成右边的







这样熔断的控制持久化就做完了,其他的规则也是这样的方法

11.项目配置文件配置

spring:
  cloud:
    sentinel:
      #控制台地址
      transport:
        dashboard: 192.168.192.136:32600
      #维护链路
      web-context-unify: false
      #取消懒加载
      eager: true
      #持久化(执行编写下面的内容)
      datasource:
        #流控规则的自定义名称
        sentinel-flow-rule:
          nacos:
            #nacos地址
            server-addr: 192.168.192.136:30001
            #nacos账号密码
            username: nacos
            password: nacos
            #命名空间
            namespace: fanmao-dev
            #组
            group-id: SENTINEL_GROUP
            #dataId
            dataId: ${spring.application.name}-flow-rules
            #规则类型为流控
            rule-type: flow
        #熔断
        sentinel-degrade-rule:
          nacos:
            #nacos地址
            server-addr: 192.168.192.136:30001
            #nacos账号密码
            username: nacos
            password: nacos
            #命名空间
            namespace: fanmao-dev
            #组
            group-id: SENTINEL_GROUP
            #dataId
            dataId: ${spring.application.name}-degrade-rules
            #规则类型为流控
            rule-type: degrade
        #系统规则
        sentinel-system-rule:
          nacos:
            #nacos地址
            server-addr: 192.168.192.136:30001
            #nacos账号密码
            username: nacos
            password: nacos
            #命名空间
            namespace: fanmao-dev
            #组
            group-id: SENTINEL_GROUP
            #dataId
            dataId: ${spring.application.name}-system-rules
            #规则类型为流控
            rule-type: system
        #热点规则
        sentinel-param-flow-rule:
          nacos:
            #nacos地址
            server-addr: 192.168.192.136:30001
            #nacos账号密码
            username: nacos
            password: nacos
            #命名空间
            namespace: fanmao-dev
            #组
            group-id: SENTINEL_GROUP
            #dataId
            dataId: ${spring.application.name}-param-flow-rules
            #规则类型为流控
            rule-type: param_flow
        #授权规则
        sentinel-authority-rule:
          nacos:
            #nacos地址
            server-addr: 192.168.192.136:30001
            #nacos账号密码
            username: nacos
            password: nacos
            #命名空间
            namespace: fanmao-dev
            #组
            group-id: SENTINEL_GROUP
            #dataId
            dataId: ${spring.application.name}-authority-rules
            #规则类型为流控
            rule-type: authority

图片圈红的部分需要注意修改

12.持久化后的配置文件名称

13.制作镜像

FROM openjdk:17.0.2-oracle
CMD ["/bin/bash"]
ENV SNAME=root SPWD=123456 SPORT=8080
ENV SNACOSSERVERADDR=127.0.0.1:8848 SNACOSNAMESPACE=dev SNACOSUSERNAME=nacos SNACOSPASSWORD=nacos
RUN mkdir -p /home/sentinel
COPY sentinel-dashboard.jar /home/sentinel/sentinel-dashboard.jar
WORKDIR /home/sentinel/
EXPOSE $SPORT
ENTRYPOINT java \
 -Dserver.port=${SPORT} \
 -Dsentinel.dashboard.auth.username=${SNAME} \
 -Dsentinel.dashboard.auth.password=${SPWD} \
 -Dsentinel.nacos.serverAddr=${SNACOSSERVERADDR} \
 -Dsentinel.nacos.namespace=${SNACOSNAMESPACE} \
 -Dsentinel.nacos.username=${SNACOSUSERNAME} \
 -Dsentinel.nacos.password=${SNACOSPASSWORD} \
 -jar /home/sentinel/sentinel-dashboard.jar

14.推送到阿里云镜像仓库

sudo docker login --username=hi*****@aliyun.com registry.cn-shenzhen.aliyuncs.com
sudo docker build -f Dockerfile -t registry.cn-shenzhen.aliyuncs.com/atomic/sentinel-dashboard-persistent-nacos:1.8.5 .
sudo docker push registry.cn-shenzhen.aliyuncs.com/atomic/sentinel-dashboard-persistent-nacos:1.8.5

15.创建工作负载

添加镜像

设置变量

16.创建服务并发访问



三、Seata

1.官网下载并解压

https://github.com/seata/seata/releases


2.编译自带的Dockerfile并发并推送到阿里云

sudo docker login --username=hi****@aliyun.com registry.cn-shenzhen.aliyuncs.com
sudo docker build -f Dockerfile -t registry.cn-shenzhen.aliyuncs.com/atomic/seata-server:1.6.1 .
sudo docker push registry.cn-shenzhen.aliyuncs.com/atomic/seata-server:1.6.1

3.创建配置字典


#  Copyright 1999-2019 Seata.io Group.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#  http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

server:
  port: 7091

spring:
  application:
    name: seata-server

logging:
  config: classpath:logback-spring.xml
  file:
    path: ${user.home}/logs/seata
  extend:
    logstash-appender:
      destination: 127.0.0.1:4560
    kafka-appender:
      bootstrap-servers: 127.0.0.1:9092
      topic: logback_to_logstash

console:
  user:
    username: seata
    password: seata

seata:
  config:
    # support: nacos, consul, apollo, zk, etcd3
    type: file
  registry:
    # support: nacos, eureka, redis, zk, consul, etcd3, sofa
    type: file
  store:
    # support: file 、 db 、 redis
    mode: file
#  server:
#    service-port: 8091 #If not configured, the default is '${server.port} + 1000'
  security:
    secretKey: SeataSecretKey0c382ef121d778043159209298fd40bf3850a017
    tokenValidityInMilliseconds: 1800000
    ignore:
      urls: /,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/api/v1/auth/login


4.创建工作负载

添加镜像和设置端口


设置子路径


5.添加服务并访问



四、Redis

1.启动命令

redis-server /usr/local/etc/redis/redis.conf


2.存储挂载以及配置挂载


3.配置文件

appendonly yes
port 6379
bind 0.0.0.0
requirepass 123456


4.客户端工具下载

https://gitee.com/qishibo/AnotherRedisDesktopManager/releases

五、RabbitMQ

1.创建存储卷

/var/lib/rabbitmq


2.设置用户名密码

RABBITMQ_DEFAULT_USER=user
RABBITMQ_DEFAULT_PASS=password 


3.暴露两个端口


15672:web访问

5672:客户端


(1)