• docker-compose安装nacos



    一、安装nacos

    安装文档:https://mrbird.cc/Spring-Cloud-Alibaba-Nacos%E6%B3%A8%E5%86%8C%E4%B8%AD%E5%BF%83.html

    docker-compose安装nacos

    创建文件夹:/opt/docker-file/nacos

    1.docker-compose.yml

    version: "3"
    services:
      nacos:
        image: nacos/nacos-server:v2.1.0
        container_name: nacos
        environment:
          # 支持主机名可以使用hostname,否则使用ip,默认ip
          - PREFER_HOST_MODE=ip
          # 单机模式
          - MODE=standalone
          # 数据源平台 支持mysql或不保存empty
          - SPRING_DATASOURCE_PLATFORM=mysql
          # mysql配置,!!!attention必须是mysql所在主机IP
          #- MYSQL_SERVICE_HOST=192.168.0.123
          #- MYSQL_SERVICE_PORT=3306
          #- MYSQL_SERVICE_USER=root
          #- MYSQL_SERVICE_PASSWORD=123456
          #- MYSQL_SERVICE_DB_NAME=nacos
        volumes:
          - ./logs:/home/nacos/logs
          - ./conf:/home/nacos/conf
        ports:
          - 8848:8848 
        restart: always
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    创建log日志目录及配置文件目录:

    mkdir -p /opt/docker-file/nacos/logs
    mkdir -p /opt/docker-file/nacos/conf	
    
    • 1
    • 2

    将application.properties文件复制到/opt/docker-file/nacos/conf目录下

    server.servlet.contextPath=/nacos
    server.port=8848
    spring.datasource.platform=mysql
    # 数据库数量
    db.num=1
    db.url.0=jdbc:mysql://192.168.229.199:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
    db.user=root2
    db.password=123456
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.nacos数据库表结构

    /*
     * 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.
     */
    
    /******************************************/
    /*   数据库全名 = nacos_config   */
    /*   表名称 = config_info   */
    /******************************************/
    CREATE TABLE `config_info` (
      `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
      `data_id` VARCHAR(255) NOT NULL COMMENT 'data_id',
      `group_id` VARCHAR(255) DEFAULT NULL,
      `content` LONGTEXT NOT NULL COMMENT 'content',
      `md5` VARCHAR(32) DEFAULT NULL COMMENT 'md5',
      `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
      `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
      `src_user` TEXT COMMENT 'source user',
      `src_ip` VARCHAR(50) DEFAULT NULL COMMENT 'source ip',
      `app_name` VARCHAR(128) DEFAULT NULL,
      `tenant_id` VARCHAR(128) DEFAULT '' COMMENT '租户字段',
      `c_desc` VARCHAR(256) DEFAULT NULL,
      `c_use` VARCHAR(64) DEFAULT NULL,
      `effect` VARCHAR(64) DEFAULT NULL,
      `type` VARCHAR(64) DEFAULT NULL,
      `c_schema` TEXT,
      `encrypted_data_key` TEXT NOT NULL COMMENT '秘钥',
      PRIMARY KEY (`id`),
      UNIQUE KEY `uk_configinfo_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info';
    
    /******************************************/
    /*   数据库全名 = nacos_config   */
    /*   表名称 = config_info_aggr   */
    /******************************************/
    CREATE TABLE `config_info_aggr` (
      `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
      `data_id` VARCHAR(255) NOT NULL COMMENT 'data_id',
      `group_id` VARCHAR(255) NOT NULL COMMENT 'group_id',
      `datum_id` VARCHAR(255) NOT NULL COMMENT 'datum_id',
      `content` LONGTEXT NOT NULL COMMENT '内容',
      `gmt_modified` DATETIME NOT NULL COMMENT '修改时间',
      `app_name` VARCHAR(128) DEFAULT NULL,
      `tenant_id` VARCHAR(128) DEFAULT '' COMMENT '租户字段',
      PRIMARY KEY (`id`),
      UNIQUE KEY `uk_configinfoaggr_datagrouptenantdatum` (`data_id`,`group_id`,`tenant_id`,`datum_id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='增加租户字段';
    
    
    /******************************************/
    /*   数据库全名 = nacos_config   */
    /*   表名称 = config_info_beta   */
    /******************************************/
    CREATE TABLE `config_info_beta` (
      `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
      `data_id` VARCHAR(255) NOT NULL COMMENT 'data_id',
      `group_id` VARCHAR(128) NOT NULL COMMENT 'group_id',
      `app_name` VARCHAR(128) DEFAULT NULL COMMENT 'app_name',
      `content` LONGTEXT NOT NULL COMMENT 'content',
      `beta_ips` VARCHAR(1024) DEFAULT NULL COMMENT 'betaIps',
      `md5` VARCHAR(32) DEFAULT NULL COMMENT 'md5',
      `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
      `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
      `src_user` TEXT COMMENT 'source user',
      `src_ip` VARCHAR(50) DEFAULT NULL COMMENT 'source ip',
      `tenant_id` VARCHAR(128) DEFAULT '' COMMENT '租户字段',
      `encrypted_data_key` TEXT NOT NULL COMMENT '秘钥',
      PRIMARY KEY (`id`),
      UNIQUE KEY `uk_configinfobeta_datagrouptenant` (`data_id`,`group_id`,`tenant_id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta';
    
    /******************************************/
    /*   数据库全名 = nacos_config   */
    /*   表名称 = config_info_tag   */
    /******************************************/
    CREATE TABLE `config_info_tag` (
      `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
      `data_id` VARCHAR(255) NOT NULL COMMENT 'data_id',
      `group_id` VARCHAR(128) NOT NULL COMMENT 'group_id',
      `tenant_id` VARCHAR(128) DEFAULT '' COMMENT 'tenant_id',
      `tag_id` VARCHAR(128) NOT NULL COMMENT 'tag_id',
      `app_name` VARCHAR(128) DEFAULT NULL COMMENT 'app_name',
      `content` LONGTEXT NOT NULL COMMENT 'content',
      `md5` VARCHAR(32) DEFAULT NULL COMMENT 'md5',
      `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
      `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
      `src_user` TEXT COMMENT 'source user',
      `src_ip` VARCHAR(50) DEFAULT NULL COMMENT 'source ip',
      PRIMARY KEY (`id`),
      UNIQUE KEY `uk_configinfotag_datagrouptenanttag` (`data_id`,`group_id`,`tenant_id`,`tag_id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';
    
    /******************************************/
    /*   数据库全名 = nacos_config   */
    /*   表名称 = config_tags_relation   */
    /******************************************/
    CREATE TABLE `config_tags_relation` (
      `id` BIGINT(20) NOT NULL COMMENT 'id',
      `tag_name` VARCHAR(128) NOT NULL COMMENT 'tag_name',
      `tag_type` VARCHAR(64) DEFAULT NULL COMMENT 'tag_type',
      `data_id` VARCHAR(255) NOT NULL COMMENT 'data_id',
      `group_id` VARCHAR(128) NOT NULL COMMENT 'group_id',
      `tenant_id` VARCHAR(128) DEFAULT '' COMMENT 'tenant_id',
      `nid` BIGINT(20) NOT NULL AUTO_INCREMENT,
      PRIMARY KEY (`nid`),
      UNIQUE KEY `uk_configtagrelation_configidtag` (`id`,`tag_name`,`tag_type`),
      KEY `idx_tenant_id` (`tenant_id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation';
    
    /******************************************/
    /*   数据库全名 = nacos_config   */
    /*   表名称 = group_capacity   */
    /******************************************/
    CREATE TABLE `group_capacity` (
      `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
      `group_id` VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'Group ID,空字符表示整个集群',
      `quota` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
      `usage` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '使用量',
      `max_size` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
      `max_aggr_count` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数,,0表示使用默认值',
      `max_aggr_size` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
      `max_history_count` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
      `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
      `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
      PRIMARY KEY (`id`),
      UNIQUE KEY `uk_group_id` (`group_id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='集群、各Group容量信息表';
    
    /******************************************/
    /*   数据库全名 = nacos_config   */
    /*   表名称 = his_config_info   */
    /******************************************/
    CREATE TABLE `his_config_info` (
      `id` BIGINT(64) UNSIGNED NOT NULL,
      `nid` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
      `data_id` VARCHAR(255) NOT NULL,
      `group_id` VARCHAR(128) NOT NULL,
      `app_name` VARCHAR(128) DEFAULT NULL COMMENT 'app_name',
      `content` LONGTEXT NOT NULL,
      `md5` VARCHAR(32) DEFAULT NULL,
      `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `src_user` TEXT,
      `src_ip` VARCHAR(50) DEFAULT NULL,
      `op_type` CHAR(10) DEFAULT NULL,
      `tenant_id` VARCHAR(128) DEFAULT '' COMMENT '租户字段',
      `encrypted_data_key` TEXT NOT NULL COMMENT '秘钥',
      PRIMARY KEY (`nid`),
      KEY `idx_gmt_create` (`gmt_create`),
      KEY `idx_gmt_modified` (`gmt_modified`),
      KEY `idx_did` (`data_id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='多租户改造';
    
    
    /******************************************/
    /*   数据库全名 = nacos_config   */
    /*   表名称 = tenant_capacity   */
    /******************************************/
    CREATE TABLE `tenant_capacity` (
      `id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
      `tenant_id` VARCHAR(128) NOT NULL DEFAULT '' COMMENT 'Tenant ID',
      `quota` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '配额,0表示使用默认值',
      `usage` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '使用量',
      `max_size` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '单个配置大小上限,单位为字节,0表示使用默认值',
      `max_aggr_count` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '聚合子配置最大个数',
      `max_aggr_size` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',
      `max_history_count` INT(10) UNSIGNED NOT NULL DEFAULT '0' COMMENT '最大变更历史数量',
      `gmt_create` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
      `gmt_modified` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '修改时间',
      PRIMARY KEY (`id`),
      UNIQUE KEY `uk_tenant_id` (`tenant_id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='租户容量信息表';
    
    
    CREATE TABLE `tenant_info` (
      `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
      `kp` VARCHAR(128) NOT NULL COMMENT 'kp',
      `tenant_id` VARCHAR(128) DEFAULT '' COMMENT 'tenant_id',
      `tenant_name` VARCHAR(128) DEFAULT '' COMMENT 'tenant_name',
      `tenant_desc` VARCHAR(256) DEFAULT NULL COMMENT 'tenant_desc',
      `create_source` VARCHAR(32) DEFAULT NULL COMMENT 'create_source',
      `gmt_create` BIGINT(20) NOT NULL COMMENT '创建时间',
      `gmt_modified` BIGINT(20) NOT NULL COMMENT '修改时间',
      PRIMARY KEY (`id`),
      UNIQUE KEY `uk_tenant_info_kptenantid` (`kp`,`tenant_id`),
      KEY `idx_tenant_id` (`tenant_id`)
    ) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info';
    
    CREATE TABLE `users` (
    	`username` VARCHAR(50) NOT NULL PRIMARY KEY,
    	`password` VARCHAR(500) NOT NULL,
    	`enabled` BOOLEAN NOT NULL
    );
    
    CREATE TABLE `roles` (
    	`username` VARCHAR(50) NOT NULL,
    	`role` VARCHAR(50) NOT NULL,
    	UNIQUE INDEX `idx_user_role` (`username` ASC, `role` ASC) USING BTREE
    );
    
    CREATE TABLE `permissions` (
        `role` VARCHAR(50) NOT NULL,
        `resource` VARCHAR(255) NOT NULL,
        `action` VARCHAR(8) NOT NULL,
        UNIQUE INDEX `uk_role_permission` (`role`,`resource`,`action`) USING BTREE
    );
    
    INSERT INTO users (username, PASSWORD, enabled) VALUES ('nacos', '$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu', TRUE);
    
    INSERT INTO roles (username, role) VALUES ('nacos', 'ROLE_ADMIN');
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222

    3.docker-compose 构建运行

    [root@localhost nacos]# docker-compose up -d
    [+] Running 1/1
     ⠿ Container nacos  Started 
    
    • 1
    • 2
    • 3

    4.检查nacos日志

    docker logs -f nacos
    
    • 1

    需要在conf目录准备log文件:nacos-logback.xml

    
    
    <configuration debug="false" scan="true" scanPeriod="1 seconds">
        <contextName>logbackcontextName>
        <property name="log.path" value="/home/nacos/logs/logback.log" />
        <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
            
            <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
                  <level>ERRORlevel>
            filter>
            <encoder>
                <pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n
                pattern>
            encoder>
        appender>
     
        <appender name="file"
            class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${log.path}file>
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
                <fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zipfileNamePattern>
            rollingPolicy>
     
            <encoder>
                <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
                pattern>
            encoder>
        appender>
     
        <root level="debug">
            <appender-ref ref="console" />
            <appender-ref ref="file" />
        root>
     
        <logger name="com.example.logback" level="warn" />
     
    configuration>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    继续查看nacos错误日志

    如连接不上数据库,就是数据库账号密码没有配对。

    6.测试访问:

    地址:192.168.229.199:49155/nacos/#/login
    账号:nacos
    密码:nacos

    TODO:

    打包成新的镜像放在本地仓库,下次可以直接用

    二、nacos为注册中心:项目测试

    nacos与springcloud与springcloudalibaba版本对照
    在这里插入图片描述
    nacos版本:v2.1.0
    springboot版本:

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.1.8.RELEASEversion>
        <relativePath/> 
    parent>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    springcloudalibaba与springcloud版本:

    <properties>
        <java.version>1.8java.version>
        <spring-cloud.version>Greenwich.RELEASEspring-cloud.version>
        <com-alibaba-cloud.version>2.1.0.RELEASEcom-alibaba-cloud.version>
    properties>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1.新建maven项目:

    在这里插入图片描述
    父:spring-cloud-alibaba-nacos-register
    子:consumer,provider

    2.配置pom.xml

    spring-cloud-alibaba-nacos-register

    
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
    
        <groupId>cc.mrbirdgroupId>
        <artifactId>spring-cloud-alibaba-nacos-registerartifactId>
        <version>1.0-SNAPSHOTversion>
        <packaging>pompackaging>
    
        <modules>
            <module>providermodule>
            <module>consumermodule>
        modules>
        <parent>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-parentartifactId>
            <version>2.1.8.RELEASEversion>
            <relativePath/> 
        parent>
    
        <properties>
            <java.version>1.8java.version>
            <spring-cloud.version>Greenwich.RELEASEspring-cloud.version>
            <com-alibaba-cloud.version>2.1.0.RELEASEcom-alibaba-cloud.version>
        properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            <dependency>
                <groupId>com.alibaba.cloudgroupId>
                <artifactId>spring-cloud-alibaba-nacos-discoveryartifactId>
            dependency>
        dependencies>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloudgroupId>
                    <artifactId>spring-cloud-dependenciesartifactId>
                    <version>${spring-cloud.version}version>
                    <type>pomtype>
                    <scope>importscope>
                dependency>
                <dependency>
                    <groupId>com.alibaba.cloudgroupId>
                    <artifactId>spring-cloud-alibaba-dependenciesartifactId>
                    <version>${com-alibaba-cloud.version}version>
                    <type>pomtype>
                    <scope>importscope>
                dependency>
            dependencies>
        dependencyManagement>
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    provider

    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
        <parent>
            <groupId>cc.mrbirdgroupId>
            <artifactId>spring-cloud-alibaba-nacos-registerartifactId>
            <version>1.0-SNAPSHOTversion>
            <relativePath>../pom.xmlrelativePath>
        parent>
    
        <artifactId>providerartifactId>
        <name>providername>
        <description>服务提供端description>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                plugin>
            plugins>
        build>
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    consumer

    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
        <parent>
            <groupId>cc.mrbirdgroupId>
            <artifactId>spring-cloud-alibaba-nacos-registerartifactId>
            <version>1.0-SNAPSHOTversion>
            <relativePath>../pom.xmlrelativePath>
        parent>
    
        <artifactId>consumerartifactId>
        <name>consumername>
        <description>服务消费端description>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                plugin>
            plugins>
        build>
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    3.配置application.properties

    provider

    server.port=8001
    spring.application.name=nacos-producer
    spring.cloud.nacos.discovery.server-addr=192.168.229.199:8848
    management.endpoints.web.exposure.include=*
    
    • 1
    • 2
    • 3
    • 4

    comsumer

    server.port=8002
    spring.application.name=nacos-consumer
    spring.cloud.nacos.discovery.server-addr=192.168.229.199:8848
    management.endpoints.web.exposure.include=*
    
    • 1
    • 2
    • 3
    • 4

    4.激活服务发现客户端

    启动类加注解@EnableDiscoveryClient

    5.编写controller

    provider

    package cc.mrbird.provider.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("provide")
    public class HelloController {
    
        @GetMapping("{message}")
        public String hello(@PathVariable String message) {
            return String.format("hello %s", message);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    consumer

    package cc.mrbird.consumer.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cloud.client.ServiceInstance;
    import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.client.RestTemplate;
    
    @RestController
    @RequestMapping("consume")
    public class ConsumeController {
    
        @Autowired
        private LoadBalancerClient loadBalancerClient;
        @Autowired
        private RestTemplate restTemplate;
    
        @GetMapping("hello/{message}")
        public String hello(@PathVariable String message) {
            ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-producer");
            String path = String.format("http://%s:%s/provide/%s", serviceInstance.getHost(), serviceInstance.getPort(), message);
            String result = restTemplate.getForObject(path, String.class);
            return String.format("%s from %s %s", result, serviceInstance.getHost(), serviceInstance.getPort());
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    6.增加远程调用配置

    consumer

    package cc.mrbird.consumer.configure;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.client.RestTemplate;
    
    @Configuration
    public class ConsumerConfigure {
    
        @Bean
        public RestTemplate restTemplate() {
            return new RestTemplate();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    7.启动后查看nacos网页端

    http://192.168.229.199:8848/nacos/#/serviceManagement
    如图:
    在这里插入图片描述

    8.访问地址

    服务提供者:localhost:8001/provide/nacos
    服务消费者:localhost:8002/consume/hello/nacos

    9.测试消费端负载均衡

    启动两个provider:
    localhost:8001/provide/nacos
    localhost:8009/provide/nacos

    在这里插入图片描述
    在这里插入图片描述

    三.nacos配置中心和注册中心:项目测试

    java项目如果启动了配置中心,在项目不重启的情况下,可以远程动态的修改配置信息

    1.新建maven项目

    在spring-cloud-alibaba-nacos-register项目下新建子项目config

    2.配置子项目pom.xml

    
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>spring-cloud-alibaba-nacos-registerartifactId>
            <groupId>cc.mrbirdgroupId>
            <version>1.0-SNAPSHOTversion>
            <relativePath>../pom.xmlrelativePath>
        parent>
        <modelVersion>4.0.0modelVersion>
    
        <artifactId>configartifactId>
        <description>配置服务description>
    
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloudgroupId>
                <artifactId>spring-cloud-alibaba-nacos-configartifactId>
            dependency>
        dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.bootgroupId>
                    <artifactId>spring-boot-maven-pluginartifactId>
                plugin>
            plugins>
        build>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    3.配置bootstrap.properties文件

    必须是bootstrap.properties文件,不然加载不到

    server.port=8102
    spring.cloud.nacos.config.server-addr=192.168.229.199:8848
    #spring.cloud.nacos.config.file-extension=properties
    spring.application.name=nacos-config-example
    
    spring.cloud.nacos.discovery.server-addr=192.168.229.199:8848
    management.endpoints.web.exposure.include=*
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4.激活服务发现客户端

    package cc.mrbird.config;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    
    @SpringBootApplication
    @EnableConfigurationProperties
    public class ConfigApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(ConfigApplication.class, args);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    5.编写controller

    package cc.mrbird.config.controller;
    
    
    import cc.mrbird.config.config.UserConfig;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("config")
    public class Controller {
    
        @Autowired
        private UserConfig userConfig;
    
        @GetMapping("hello/{message}")
        public String sayHello(@PathVariable String message) {
            return this.userConfig.getUsername() + message + ";" + this.userConfig.getAge();
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    6.编写bean,获取远程配置

    package cc.mrbird.config.config;
    
    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.stereotype.Component;
    
    @ConfigurationProperties(prefix = "user")
    //@Component
    @Configuration
    @Data
    public class UserConfig {
    
        private String username;
    
        private int age;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    7.在nacos服务端上增加配置

    注意dataId的命名方式
    在这里插入图片描述

    8.启动config项目

    没有报错,说明配置没有问题

    9.访问controller

    localhost:8102/config/hello/nacos

    修改nacos服务端配置后再次访问:成功

    四、整合gateway网关

    1.添加依赖

    注释web依赖
    
    
    
    
    
    <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-starter-gatewayartifactId>
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.bootgroupId>
                        <artifactId>spring-boot-starter-webartifactId>
                    exclusion>
                exclusions>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    2.编写配置文件

    spring:
      gateway:
          routes:
            - id: gateway-test  # 访问http://localhost:8801/gateway-test/test/index,会跳转到访问到 http://localhost:8802/gateway-test/test/index地址
              uri: lb://gateway-test
              order: 0
              predicates:
                - Path=/gateway-test/**
              filters:
                - StripPrefix=1
                
    management:
      endpoints:
        web:
          exposure:
            include: '*'
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    3.启动项目

    4.如何测试网关是否拦截了目标服务器请求

  • 相关阅读:
    专利说明书怎么写?
    Django REST项目实战:在线中文字符识别
    structs2 重构成SpringBoot架构
    使用正交表设计测试用例
    P1016 [NOIP1999 提高组] 旅行家的预算——题解
    Baklib知识分享|企业产品需求文档的特点
    “Docker:革新应用程序开发和部署“
    02-Nacos的服务注册与发现
    算法分析与设计编程题 回溯法
    多云容器集群服务的设计与实现
  • 原文地址:https://blog.csdn.net/User_bie/article/details/128083642