Spring Cloud Alibaba之Nacos单机、集群配置以及springboot整合

Spring Cloud Alibaba是阿里的一套spring cloud解决方案,感觉比传统的springcloud要更强大易用,总结了一下,一套完整的Spring Cloud Alibaba可以包括下面一些微服务组件:

服务注册与发现、配置中心:nacos
api网关:gateway或自研网关
限流降级、服务熔断:sentinel
服务调用:openFeign、springCloudLoadBalancer、Ribbon负载均衡、seata分布式事务
消息驱动:RocketMQ
数据层:redis、mysql、elasticSearch、mongodb

今天的主角是nacos,兼有服务注册与发现和配置中心的功能,而在传统的springCloud中这两个功能分别需要SpringCloud Eureka和SpringCloud Config。
官网:https://nacos.io/zh-cn/docs/quick-start.html

ubuntu安装nacos

下载地址:https://github.com/alibaba/nacos/releases(github网速极慢,下了好久。)
截止发文前最新版本是2.0.0-bugfix (Mar 30th, 2021)
下载后解压:tar -zxvf nacos-server-2.0.0.tar.gz

单机模式

在解压路径bin目录下执行启动命令(-m standalone是单机模式,如果不加后缀默认是集群模式,占用内存较多)

./startup.sh -m standalone

执行结果日志如下(使用tail /app/nacos/logs/start.out查看注册中心运行日志):

/home/zhaohy/myspace/software/jdk1.8.0_181/bin/java  -Xms512m -Xmx512m -Xmn256m -Dnacos.standalone=true -Dnacos.member.list= -Djava.ext.dirs=/home/zhaohy/myspace/software/jdk1.8.0_181/jre/lib/ext:/home/zhaohy/myspace/software/jdk1.8.0_181/lib/ext -Xloggc:/home/zhaohy/myspace/profiles/nacos-server-2.0.0/nacos/logs/nacos_gc.log -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M -Dloader.path=/home/zhaohy/myspace/profiles/nacos-server-2.0.0/nacos/plugins/health,/home/zhaohy/myspace/profiles/nacos-server-2.0.0/nacos/plugins/cmdb -Dnacos.home=/home/zhaohy/myspace/profiles/nacos-server-2.0.0/nacos -jar /home/zhaohy/myspace/profiles/nacos-server-2.0.0/nacos/target/nacos-server.jar  --spring.config.additional-location=file:/home/zhaohy/myspace/profiles/nacos-server-2.0.0/nacos/conf/ --logging.config=/home/zhaohy/myspace/profiles/nacos-server-2.0.0/nacos/conf/nacos-logback.xml --server.max-http-header-size=524288

         ,--.
       ,--.'|
   ,--,:  : |                                           Nacos 2.0.0
,`--.'`|  ' :                       ,---.               Running in stand alone mode, All function modules
|   :  :  | |                      '   ,'\   .--.--.    Port: 8848
:   |   \ | :  ,--.--.     ,---.  /   /   | /  /    '   Pid: 10243
|   : '  '; | /       \   /     \.   ; ,. :|  :  /`./   Console: http://192.168.0.109:8848/nacos/index.html
'   ' ;.    ;.--.  .-. | /    / ''   | |: :|  :  ;_
|   | | \   | \__\/: . ..    ' / '   | .; : \  \    `.      https://nacos.io
'   : |  ; .' ," .--.; |'   ; :__|   :    |  `----.   \
|   | '`--'  /  /  ,.  |'   | '.'|\   \  /  /  /`--'  /
'   : |     ;  :   .'   \   :    : `----'  '--'.     /
;   |.'     |  ,     .-./\   \  /            `--'---'
'---'        `--`---'     `----'

2021-04-04 15:10:53,199 INFO Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler@4a67318f' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2021-04-04 15:10:53,203 INFO Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

2021-04-04 15:10:53,484 INFO Tomcat initialized with port(s): 8848 (http)

2021-04-04 15:10:53,782 INFO Root WebApplicationContext: initialization completed in 3885 ms

2021-04-04 15:10:57,960 INFO Initializing ExecutorService 'applicationTaskExecutor'

2021-04-04 15:10:58,059 INFO Adding welcome page: class path resource [static/index.html]

2021-04-04 15:10:58,369 INFO Creating filter chain: Ant [pattern='/**'], []

2021-04-04 15:10:58,396 INFO Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@238bfd6c, org.springframework.security.web.context.SecurityContextPersistenceFilter@700f518a, org.springframework.security.web.header.HeaderWriterFilter@602ae7b6, org.springframework.security.web.csrf.CsrfFilter@59901c4d, org.springframework.security.web.authentication.logout.LogoutFilter@68e7c8c3, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@13da7ab0, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@3724b43e, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@ef1695a, org.springframework.security.web.session.SessionManagementFilter@71ad3d8a, org.springframework.security.web.access.ExceptionTranslationFilter@d8d9199]

2021-04-04 15:10:58,477 INFO Initializing ExecutorService 'taskScheduler'

2021-04-04 15:10:58,495 INFO Exposing 16 endpoint(s) beneath base path '/actuator'

2021-04-04 15:10:58,575 INFO Tomcat started on port(s): 8848 (http) with context path '/nacos'

2021-04-04 15:10:58,577 INFO Nacos started successfully in stand alone mode. use embedded storage

日志文件保存在/logs/start.out和/logs/nacos.log文件下

根据日志可以看到占了512m内存,默认是8848端口
浏览器访问本机8848,用户名密码默认都是nacos:http://192.168.0.109:8848/nacos/index.html

nacos启动登录界面

nacos-index.html界面

如上图可以看到启动成功,成功进入运维界面。

这样启动默认用的是nacos内嵌的数据库,也可以指定mysql数据库,方便看数据。

配置mysql

在/conf文件夹下nacos提供了mysql建表语句,存储在nacos-mysql.sql文件里
文件如下:

/*
 * 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,
  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 '租户字段',
  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 '租户字段',
  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');

打开Mysql创建nacos_config库,导入conf下nacos-mysql.sql文件
创建后如图:


nacos_config库表截图

修改application.properties中连接数据库信息,将spring.datasource.platform=mysql,db.num=1放开
修改db.url.0 ,db.user.0,db.password.0 换成自己的配置

在bin路径下停掉nacos,重启

./shutdown.sh
./startup.sh -m standalone

springboot整合nacos

在nacos里新建dev开发环境命名空间,新建之后会自动生成一个命名空间id。


在nacos里新建命名空间

在dev命名空间下新建如下配置(刚好这个配置和springboot项目spring.application.name是一样的):


dev下新建项目配置示例

引入以下三个依赖包
spring-cloud-starter-alibaba-nacos-config 配置中心
spring-cloud-starter-alibaba-nacos-discovery注册中心
nacos-client 客户端(如果服务里不编写自动发布脚本,这个引不引都没关系)
springboot项目里maven引入:

      <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
            <version>2.0.0</version>
        </dependency>

在bootstrap.yml里加入以下配置:

spring:
  application:
    name: springbootSSM-myblog-nacos
  cloud:
    ###############Nacos Config Star##################
    nacos:
      config:
        # nacos contextPath
        context-path: /nacos
        # 公共的配置,刷新默认关闭
        extension-configs:
           - data-id: application.yaml
             group: MY_GROUP
           - data-id: RocketMQ.yaml
             group: MY_GROUP
        # 命名空间ID(隔离不同的环境)
        namespace: ${spring.cloud.nacos.discovery.namespace}
        # nacos配置中心地址
        server-addr: ${spring.cloud.nacos.discovery.server-addr}
        # 默认的配置管理组
        group: MY_GROUP
      discovery:
        # nacos注册地址
        server-addr: 192.168.0.109:8848
        # 默认的注册服务组
        group: DEFAULT_GROUP
        # 服务注册命名空间ID(隔离不同的环境)
        namespace: f6c41257-f75e-4ddd-b678-8deb4fceeec2
      # nacos账号密码
      password: nacos
      username: nacos
    ###############Nacos Config End##################

上面定义的spring.application.name刚好是nacos里面的配置名,这样就不用单独写出来,默认会把这个配置项加载进来,MY_GROUP下的其他配置如上面定义的application.yaml,RocketMQ.yaml等则需要写在这里引入进来,这里省略不写了这两个配置,上面的namespace填的是上面新建dev命名空间时生成的id。

添加注解

在SpringBoot启动类上添加@EnableDiscoveryClient即可,注意如果之前从Eureka注册中心切换过来需要移除@EnableEurekaClient等其他注册中心客户端注解

package com.zhaohy.app;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.zhaohy.app.sys.filter.LoginProcessFilter;
import com.zhaohy.app.utils.OnLineCountListener;

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
@MapperScan("com.zhaohy.app.dao")
//@ImportResource({"classpath:applicationContext.xml"})
@EnableDiscoveryClient
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
        System.out.println("springboot started...");
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Bean
    public FilterRegistrationBean myFilterRegistration() {
        FilterRegistrationBean regist = new FilterRegistrationBean(new LoginProcessFilter());
        // 过滤全部请求
        regist.addUrlPatterns("/*");//过滤url
        regist.setOrder(1);//过滤器顺序
        return regist;
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Bean
    public ServletListenerRegistrationBean listenerRegist() {
        ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
        srb.setListener(new OnLineCountListener());
        System.out.println("listener====");
        return srb;
    }
}

如此项目启动的时候就可以把nacos里定义的配置加载到spring里了

测试

新建SpringContextUtil

package com.zhaohy.app.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext; // Spring应用上下文环境
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        return (T) applicationContext.getBean(name);
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<?> clz) throws BeansException {
        return (T) applicationContext.getBean(clz);
    }
}

启动类修改:

package com.zhaohy.app;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.core.env.Environment;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure;
import com.zhaohy.app.entity.TestEntity;
import com.zhaohy.app.sys.filter.LoginProcessFilter;
import com.zhaohy.app.utils.OnLineCountListener;
import com.zhaohy.app.utils.SpringContextUtil;

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
@MapperScan("com.zhaohy.app.dao")
@Import({SpringContextUtil.class})
//@ImportResource({"classpath:applicationContext.xml"})
@EnableDiscoveryClient
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
        System.out.println("springboot started...");
        Environment config = SpringContextUtil.getApplicationContext().getEnvironment();
        String value = config.getProperty("error_msg_1_cn");
        System.out.println("=====" + value);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Bean
    public FilterRegistrationBean myFilterRegistration() {
        FilterRegistrationBean regist = new FilterRegistrationBean(new LoginProcessFilter());
        // 过滤全部请求
        regist.addUrlPatterns("/*");//过滤url
        regist.setOrder(1);//过滤器顺序
        return regist;
    }
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Bean
    public ServletListenerRegistrationBean listenerRegist() {
        ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
        srb.setListener(new OnLineCountListener());
        System.out.println("listener====");
        return srb;
    }
}

运行之后可以在控制台输出看到配置获取成功:

springboot started...
=====成功

nacos服务列表也能看到上线的服务了:


nacos服务列表截图

nacos集群

在三台机子上分别部署nacos,在nacos的解压目录nacos/的conf目录下,有配置文件cluster.conf.example,需要自行复制一份,修改名称为cluster.conf,每行配置成ip:port。(配置3个或3个以上节点)

192.168.0.109:8848
192.168.0.110:8848
192.168.0.111:8848

mysql三台机子连接同一个,分别启动三台机子上的nacos(这次不用加后缀,默认是集群模式)

./startup.sh

启动之后,用浏览器分别访问这三台机子的8848
http://192.168.0.109:8848/nacos/index.html
http://192.168.0.110:8848/nacos/index.html
http://192.168.0.111:8848/nacos/index.html
会发现三台都启动成功了。
集群管理下的节点列表出现了三个地址。
springboot项目中bootstrap.yml里只需修改

spring.cloud.nacos.config.server-addr=192.168.0.109:8848,192.168.0.110:8848,192.168.0.111:8848

(为方便写在这里,写了properties的格式,yml里要有yml的格式)
但是这样的配置方式在实际使用上可能会比较麻烦,因为生产环境中的微服务往往有很多个,如果以后加nacos服务器,那这么多的微服务都要更改一遍吗,还可以用nginx转发到集群节点,这样springboot中只要配置一个nginx固定地址就好了,加机器只要统一更改nginx上的转发路径就可以了。

注意:集群模式下要用真机,不要用改端口的伪集群了,除了8848端口外,即便是改了不同的端口,启动的时候还是会报其他端口占用,三台不同机子的成功率大一点。

参考:https://blog.csdn.net/qq_32352777/article/details/86560333
https://www.jianshu.com/p/4b5d10bdf923

======20240523更新====

安装2.2.3版本时遇到点问题,记录一下。

nacos从2.2.2开始,默认不启用登录界面,鉴权描述如下:

https://nacos.io/zh-cn/docs/v2/guide/user/auth.html

2.2.2版本之前的Nacos默认控制台,无论服务端是否开启鉴权,都会存在一个登录页;这导致很多用户被误导认为Nacos默认是存在鉴权的。在社区安全工程师的建议下,Nacos自2.2.2版本开始,在未开启鉴权时,默认控制台将不需要登录即可访问,同时在控制台中给予提示,提醒用户当前集群未开启鉴权。

在用户开启鉴权后,控制台才需要进行登录访问。

参考如下链接解决了这个问题:

https://blog.csdn.net/qfyh_djh/article/details/137006862

修改application.properties里的

#开启鉴权
nacos.core.auth.enabled=true
#关闭使用 user-agent 判断服务端请求并放行鉴权的功能  
nacos.core.auth.enable.userAgentAuthWhite=false
#权限缓存开关,开启后权限缓存的更新默认有15秒的延迟,默认 : false
nacos.core.auth.caching.enabled=true
#配置自定义身份识别的 key 和 value (不可为空)
nacos.core.auth.server.identity.key=nacos
nacos.core.auth.server.identity.value=nacos
#自定义用于生成JWT令牌的密钥,注意:原始密钥长度不得低于32字符,且一定要进行Base64编码,否则无法启动节点。
nacos.core.auth.plugin.nacos.token.secret.key=${NACOS_AUTH_TOKEN:SecretKey01234567890123456789012345345678999987654901234567890123456789}

重启nacos集群之后,就有登录界面了。

======20240831更新======

补充下nacos集群的nginx配置:
http:8848

upstream nacoscluster{
  server 192.168.0.109:8848;
  server 192.168.0.110:8848;
  server 192.168.0.111:8848;
  ip_hash;
}
server {
    listen 8848;
    location / {
        proxy_pass http://nacoscluster;
        include proxy.conf;
    }
}

tcp:9848

stream {

  upstream nacos-cluster-tcp {
     server 192.168.0.109:9848;
     server 192.168.0.110:9848;
     server 192.168.0.111:9848;
  }

  server {
       listen 9848;
       proxy_pass nacos-cluster-tcp;
  }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
禁止转载,如需转载请通过简信或评论联系作者。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,968评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,682评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,254评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,074评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,964评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,055评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,484评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,170评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,433评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,512评论 2 308
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,296评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,184评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,545评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,150评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,437评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,630评论 2 335

推荐阅读更多精彩内容