Spring Cloud Alibaba之Nacos单机、集群配

2021-04-04  本文已影响0人  haiyong6

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

上一篇下一篇

猜你喜欢

热点阅读