文章目录
一、安装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=nacosvolumes:- ./logs:/home/nacos/logs
- ./conf:/home/nacos/conf
ports:- 8848:8848restart: always
创建log日志目录及配置文件目录:
mkdir-p /opt/docker-file/nacos/logs
mkdir-p /opt/docker-file/nacos/conf
将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
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 *//******************************************/CREATETABLE`config_info`(`id`BIGINT(20)NOTNULLAUTO_INCREMENTCOMMENT'id',`data_id`VARCHAR(255)NOTNULLCOMMENT'data_id',`group_id`VARCHAR(255)DEFAULTNULL,`content`LONGTEXTNOTNULLCOMMENT'content',`md5`VARCHAR(32)DEFAULTNULLCOMMENT'md5',`gmt_create`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'创建时间',`gmt_modified`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'修改时间',`src_user`TEXTCOMMENT'source user',`src_ip`VARCHAR(50)DEFAULTNULLCOMMENT'source ip',`app_name`VARCHAR(128)DEFAULTNULL,`tenant_id`VARCHAR(128)DEFAULT''COMMENT'租户字段',`c_desc`VARCHAR(256)DEFAULTNULL,`c_use`VARCHAR(64)DEFAULTNULL,`effect`VARCHAR(64)DEFAULTNULL,`type`VARCHAR(64)DEFAULTNULL,`c_schema`TEXT,`encrypted_data_key`TEXTNOTNULLCOMMENT'秘钥',PRIMARYKEY(`id`),UNIQUEKEY`uk_configinfo_datagrouptenant`(`data_id`,`group_id`,`tenant_id`))ENGINE=INNODBDEFAULTCHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info';/******************************************//* 数据库全名 = nacos_config *//* 表名称 = config_info_aggr *//******************************************/CREATETABLE`config_info_aggr`(`id`BIGINT(20)NOTNULLAUTO_INCREMENTCOMMENT'id',`data_id`VARCHAR(255)NOTNULLCOMMENT'data_id',`group_id`VARCHAR(255)NOTNULLCOMMENT'group_id',`datum_id`VARCHAR(255)NOTNULLCOMMENT'datum_id',`content`LONGTEXTNOTNULLCOMMENT'内容',`gmt_modified`DATETIMENOTNULLCOMMENT'修改时间',`app_name`VARCHAR(128)DEFAULTNULL,`tenant_id`VARCHAR(128)DEFAULT''COMMENT'租户字段',PRIMARYKEY(`id`),UNIQUEKEY`uk_configinfoaggr_datagrouptenantdatum`(`data_id`,`group_id`,`tenant_id`,`datum_id`))ENGINE=INNODBDEFAULTCHARSET=utf8 COLLATE=utf8_bin COMMENT='增加租户字段';/******************************************//* 数据库全名 = nacos_config *//* 表名称 = config_info_beta *//******************************************/CREATETABLE`config_info_beta`(`id`BIGINT(20)NOTNULLAUTO_INCREMENTCOMMENT'id',`data_id`VARCHAR(255)NOTNULLCOMMENT'data_id',`group_id`VARCHAR(128)NOTNULLCOMMENT'group_id',`app_name`VARCHAR(128)DEFAULTNULLCOMMENT'app_name',`content`LONGTEXTNOTNULLCOMMENT'content',`beta_ips`VARCHAR(1024)DEFAULTNULLCOMMENT'betaIps',`md5`VARCHAR(32)DEFAULTNULLCOMMENT'md5',`gmt_create`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'创建时间',`gmt_modified`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'修改时间',`src_user`TEXTCOMMENT'source user',`src_ip`VARCHAR(50)DEFAULTNULLCOMMENT'source ip',`tenant_id`VARCHAR(128)DEFAULT''COMMENT'租户字段',`encrypted_data_key`TEXTNOTNULLCOMMENT'秘钥',PRIMARYKEY(`id`),UNIQUEKEY`uk_configinfobeta_datagrouptenant`(`data_id`,`group_id`,`tenant_id`))ENGINE=INNODBDEFAULTCHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_beta';/******************************************//* 数据库全名 = nacos_config *//* 表名称 = config_info_tag *//******************************************/CREATETABLE`config_info_tag`(`id`BIGINT(20)NOTNULLAUTO_INCREMENTCOMMENT'id',`data_id`VARCHAR(255)NOTNULLCOMMENT'data_id',`group_id`VARCHAR(128)NOTNULLCOMMENT'group_id',`tenant_id`VARCHAR(128)DEFAULT''COMMENT'tenant_id',`tag_id`VARCHAR(128)NOTNULLCOMMENT'tag_id',`app_name`VARCHAR(128)DEFAULTNULLCOMMENT'app_name',`content`LONGTEXTNOTNULLCOMMENT'content',`md5`VARCHAR(32)DEFAULTNULLCOMMENT'md5',`gmt_create`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'创建时间',`gmt_modified`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'修改时间',`src_user`TEXTCOMMENT'source user',`src_ip`VARCHAR(50)DEFAULTNULLCOMMENT'source ip',PRIMARYKEY(`id`),UNIQUEKEY`uk_configinfotag_datagrouptenanttag`(`data_id`,`group_id`,`tenant_id`,`tag_id`))ENGINE=INNODBDEFAULTCHARSET=utf8 COLLATE=utf8_bin COMMENT='config_info_tag';/******************************************//* 数据库全名 = nacos_config *//* 表名称 = config_tags_relation *//******************************************/CREATETABLE`config_tags_relation`(`id`BIGINT(20)NOTNULLCOMMENT'id',`tag_name`VARCHAR(128)NOTNULLCOMMENT'tag_name',`tag_type`VARCHAR(64)DEFAULTNULLCOMMENT'tag_type',`data_id`VARCHAR(255)NOTNULLCOMMENT'data_id',`group_id`VARCHAR(128)NOTNULLCOMMENT'group_id',`tenant_id`VARCHAR(128)DEFAULT''COMMENT'tenant_id',`nid`BIGINT(20)NOTNULLAUTO_INCREMENT,PRIMARYKEY(`nid`),UNIQUEKEY`uk_configtagrelation_configidtag`(`id`,`tag_name`,`tag_type`),KEY`idx_tenant_id`(`tenant_id`))ENGINE=INNODBDEFAULTCHARSET=utf8 COLLATE=utf8_bin COMMENT='config_tag_relation';/******************************************//* 数据库全名 = nacos_config *//* 表名称 = group_capacity *//******************************************/CREATETABLE`group_capacity`(`id`BIGINT(20)UNSIGNEDNOTNULLAUTO_INCREMENTCOMMENT'主键ID',`group_id`VARCHAR(128)NOTNULLDEFAULT''COMMENT'Group ID,空字符表示整个集群',`quota`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'配额,0表示使用默认值',`usage`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'使用量',`max_size`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'单个配置大小上限,单位为字节,0表示使用默认值',`max_aggr_count`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'聚合子配置最大个数,,0表示使用默认值',`max_aggr_size`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',`max_history_count`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'最大变更历史数量',`gmt_create`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'创建时间',`gmt_modified`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'修改时间',PRIMARYKEY(`id`),UNIQUEKEY`uk_group_id`(`group_id`))ENGINE=INNODBDEFAULTCHARSET=utf8 COLLATE=utf8_bin COMMENT='集群、各Group容量信息表';/******************************************//* 数据库全名 = nacos_config *//* 表名称 = his_config_info *//******************************************/CREATETABLE`his_config_info`(`id`BIGINT(64)UNSIGNEDNOTNULL,`nid`BIGINT(20)UNSIGNEDNOTNULLAUTO_INCREMENT,`data_id`VARCHAR(255)NOTNULL,`group_id`VARCHAR(128)NOTNULL,`app_name`VARCHAR(128)DEFAULTNULLCOMMENT'app_name',`content`LONGTEXTNOTNULL,`md5`VARCHAR(32)DEFAULTNULL,`gmt_create`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMP,`gmt_modified`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMP,`src_user`TEXT,`src_ip`VARCHAR(50)DEFAULTNULL,`op_type`CHAR(10)DEFAULTNULL,`tenant_id`VARCHAR(128)DEFAULT''COMMENT'租户字段',`encrypted_data_key`TEXTNOTNULLCOMMENT'秘钥',PRIMARYKEY(`nid`),KEY`idx_gmt_create`(`gmt_create`),KEY`idx_gmt_modified`(`gmt_modified`),KEY`idx_did`(`data_id`))ENGINE=INNODBDEFAULTCHARSET=utf8 COLLATE=utf8_bin COMMENT='多租户改造';/******************************************//* 数据库全名 = nacos_config *//* 表名称 = tenant_capacity *//******************************************/CREATETABLE`tenant_capacity`(`id`BIGINT(20)UNSIGNEDNOTNULLAUTO_INCREMENTCOMMENT'主键ID',`tenant_id`VARCHAR(128)NOTNULLDEFAULT''COMMENT'Tenant ID',`quota`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'配额,0表示使用默认值',`usage`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'使用量',`max_size`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'单个配置大小上限,单位为字节,0表示使用默认值',`max_aggr_count`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'聚合子配置最大个数',`max_aggr_size`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'单个聚合数据的子配置大小上限,单位为字节,0表示使用默认值',`max_history_count`INT(10)UNSIGNEDNOTNULLDEFAULT'0'COMMENT'最大变更历史数量',`gmt_create`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'创建时间',`gmt_modified`DATETIMENOTNULLDEFAULTCURRENT_TIMESTAMPCOMMENT'修改时间',PRIMARYKEY(`id`),UNIQUEKEY`uk_tenant_id`(`tenant_id`))ENGINE=INNODBDEFAULTCHARSET=utf8 COLLATE=utf8_bin COMMENT='租户容量信息表';CREATETABLE`tenant_info`(`id`BIGINT(20)NOTNULLAUTO_INCREMENTCOMMENT'id',`kp`VARCHAR(128)NOTNULLCOMMENT'kp',`tenant_id`VARCHAR(128)DEFAULT''COMMENT'tenant_id',`tenant_name`VARCHAR(128)DEFAULT''COMMENT'tenant_name',`tenant_desc`VARCHAR(256)DEFAULTNULLCOMMENT'tenant_desc',`create_source`VARCHAR(32)DEFAULTNULLCOMMENT'create_source',`gmt_create`BIGINT(20)NOTNULLCOMMENT'创建时间',`gmt_modified`BIGINT(20)NOTNULLCOMMENT'修改时间',PRIMARYKEY(`id`),UNIQUEKEY`uk_tenant_info_kptenantid`(`kp`,`tenant_id`),KEY`idx_tenant_id`(`tenant_id`))ENGINE=INNODBDEFAULTCHARSET=utf8 COLLATE=utf8_bin COMMENT='tenant_info';CREATETABLE`users`(`username`VARCHAR(50)NOTNULLPRIMARYKEY,`password`VARCHAR(500)NOTNULL,`enabled`BOOLEANNOTNULL);CREATETABLE`roles`(`username`VARCHAR(50)NOTNULL,`role`VARCHAR(50)NOTNULL,UNIQUEINDEX`idx_user_role`(`username`ASC,`role`ASC)USINGBTREE);CREATETABLE`permissions`(`role`VARCHAR(50)NOTNULL,`resource`VARCHAR(255)NOTNULL,`action`VARCHAR(8)NOTNULL,UNIQUEINDEX`uk_role_permission`(`role`,`resource`,`action`)USINGBTREE);INSERTINTO users (username, PASSWORD, enabled)VALUES('nacos','$2a$10$EuWPZHzz32dJN7jexM34MOeYirDdFAZm2kuWj7VEOJhhZkDrxfvUu',TRUE);INSERTINTO roles (username, role)VALUES('nacos','ROLE_ADMIN');
3.docker-compose 构建运行
[root@localhost nacos]# docker-compose up -d[+] Running 1/1
⠿ Container nacos Started
4.检查nacos日志
docker logs -f nacos
需要在conf目录准备log文件:nacos-logback.xml
<?xml version="1.0" encoding="UTF-8"?><configurationdebug="false"scan="true"scanPeriod="1 seconds"><contextName>logback</contextName><propertyname="log.path"value="/home/nacos/logs/logback.log"/><appendername="console"class="ch.qos.logback.core.ConsoleAppender"><!-- <filter class="com.example.logback.filter.MyFilter" /> --><filterclass="ch.qos.logback.classic.filter.ThresholdFilter"><level>ERROR</level></filter><encoder><pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n
</pattern></encoder></appender><appendername="file"class="ch.qos.logback.core.rolling.RollingFileAppender"><file>${log.path}</file><rollingPolicyclass="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><fileNamePattern>${log.path}.%d{yyyy-MM-dd}.zip</fileNamePattern></rollingPolicy><encoder><pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
</pattern></encoder></appender><rootlevel="debug"><appender-refref="console"/><appender-refref="file"/></root><loggername="com.example.logback"level="warn"/></configuration>
继续查看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.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.8.RELEASE</version><relativePath/><!-- lookup parent from repository --></parent>
springcloudalibaba与springcloud版本:
<properties><java.version>1.8</java.version><spring-cloud.version>Greenwich.RELEASE</spring-cloud.version><com-alibaba-cloud.version>2.1.0.RELEASE</com-alibaba-cloud.version></properties>
1.新建maven项目:
父:spring-cloud-alibaba-nacos-register
子:consumer,provider
2.配置pom.xml
spring-cloud-alibaba-nacos-register
<?xml version="1.0" encoding="UTF-8"?><projectxmlns="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.0</modelVersion><groupId>cc.mrbird</groupId><artifactId>spring-cloud-alibaba-nacos-register</artifactId><version>1.0-SNAPSHOT</version><packaging>pom</packaging><modules><module>provider</module><module>consumer</module></modules><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.8.RELEASE</version><relativePath/><!-- lookup parent from repository --></parent><properties><java.version>1.8</java.version><spring-cloud.version>Greenwich.RELEASE</spring-cloud.version><com-alibaba-cloud.version>2.1.0.RELEASE</com-alibaba-cloud.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-nacos-discovery</artifactId></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>${com-alibaba-cloud.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement></project>
provider
<?xml version="1.0" encoding="UTF-8"?><projectxmlns="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.0</modelVersion><parent><groupId>cc.mrbird</groupId><artifactId>spring-cloud-alibaba-nacos-register</artifactId><version>1.0-SNAPSHOT</version><relativePath>../pom.xml</relativePath></parent><artifactId>provider</artifactId><name>provider</name><description>服务提供端</description><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
consumer
<?xml version="1.0" encoding="UTF-8"?><projectxmlns="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.0</modelVersion><parent><groupId>cc.mrbird</groupId><artifactId>spring-cloud-alibaba-nacos-register</artifactId><version>1.0-SNAPSHOT</version><relativePath>../pom.xml</relativePath></parent><artifactId>consumer</artifactId><name>consumer</name><description>服务消费端</description><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
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=*
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=*
4.激活服务发现客户端
启动类加注解@EnableDiscoveryClient
5.编写controller
provider
packagecc.mrbird.provider.controller;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("provide")publicclassHelloController{@GetMapping("{message}")publicStringhello(@PathVariableString message){returnString.format("hello %s", message);}}
consumer
packagecc.mrbird.consumer.controller;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.cloud.client.ServiceInstance;importorg.springframework.cloud.client.loadbalancer.LoadBalancerClient;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.client.RestTemplate;@RestController@RequestMapping("consume")publicclassConsumeController{@AutowiredprivateLoadBalancerClient loadBalancerClient;@AutowiredprivateRestTemplate restTemplate;@GetMapping("hello/{message}")publicStringhello(@PathVariableString 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);returnString.format("%s from %s %s", result, serviceInstance.getHost(), serviceInstance.getPort());}}
6.增加远程调用配置
consumer
packagecc.mrbird.consumer.configure;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.client.RestTemplate;@ConfigurationpublicclassConsumerConfigure{@BeanpublicRestTemplaterestTemplate(){returnnewRestTemplate();}}
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
<?xml version="1.0" encoding="UTF-8"?><projectxmlns="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-register</artifactId><groupId>cc.mrbird</groupId><version>1.0-SNAPSHOT</version><relativePath>../pom.xml</relativePath></parent><modelVersion>4.0.0</modelVersion><artifactId>config</artifactId><description>配置服务</description><dependencies><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-nacos-config</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
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=*
4.激活服务发现客户端
packagecc.mrbird.config;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.context.properties.EnableConfigurationProperties;@SpringBootApplication@EnableConfigurationPropertiespublicclassConfigApplication{publicstaticvoidmain(String[] args){SpringApplication.run(ConfigApplication.class, args);}}
5.编写controller
packagecc.mrbird.config.controller;importcc.mrbird.config.config.UserConfig;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("config")publicclassController{@AutowiredprivateUserConfig userConfig;@GetMapping("hello/{message}")publicStringsayHello(@PathVariableString message){returnthis.userConfig.getUsername()+ message +";"+this.userConfig.getAge();}}
6.编写bean,获取远程配置
packagecc.mrbird.config.config;importlombok.Data;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.boot.context.properties.EnableConfigurationProperties;importorg.springframework.context.annotation.Configuration;importorg.springframework.stereotype.Component;@ConfigurationProperties(prefix ="user")//@Component@Configuration@DatapublicclassUserConfig{privateString username;privateint age;}
7.在nacos服务端上增加配置
注意dataId的命名方式
8.启动config项目
没有报错,说明配置没有问题
9.访问controller
localhost:8102/config/hello/nacos
修改nacos服务端配置后再次访问:成功
四、整合gateway网关
1.添加依赖
注释web依赖
<!-- <dependency>--><!-- <groupId>org.springframework.boot</groupId>--><!-- <artifactId>spring-boot-starter-web</artifactId>--><!-- </dependency>--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></exclusion></exclusions></dependency>
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:0predicates:- Path=/gateway-test/**filters:- StripPrefix=1
management:endpoints:web:exposure:include:'*'
3.启动项目
4.如何测试网关是否拦截了目标服务器请求
版权归原作者 seeyoutlb 所有, 如有侵权,请联系我们删除。