Spring Cloud Alibaba是阿里的一套spring cloud解決方案,感覺比傳統(tǒng)的springcloud要更強大易用,總結(jié)了一下,一套完整的Spring Cloud Alibaba可以包括下面一些微服務(wù)組件:
服務(wù)注冊與發(fā)現(xiàn)、配置中心:nacos
api網(wǎng)關(guān):gateway或自研網(wǎng)關(guān)
限流降級、服務(wù)熔斷:sentinel
服務(wù)調(diào)用:openFeign、springCloudLoadBalancer、Ribbon負載均衡、seata分布式事務(wù)
消息驅(qū)動:RocketMQ
數(shù)據(jù)層:redis、mysql、elasticSearch、mongodb
今天的主角是nacos,兼有服務(wù)注冊與發(fā)現(xiàn)和配置中心的功能,而在傳統(tǒng)的springCloud中這兩個功能分別需要SpringCloud Eureka和SpringCloud Config。
官網(wǎng):https://nacos.io/zh-cn/docs/quick-start.html
ubuntu安裝nacos
下載地址:https://github.com/alibaba/nacos/releases(github網(wǎng)速極慢,下了好久。)
截止發(fā)文前最新版本是2.0.0-bugfix (Mar 30th, 2021)
下載后解壓:tar -zxvf nacos-server-2.0.0.tar.gz
單機模式
在解壓路徑bin目錄下執(zhí)行啟動命令(-m standalone是單機模式,如果不加后綴默認是集群模式,占用內(nèi)存較多)
./startup.sh -m standalone
執(zhí)行結(jié)果日志如下(使用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文件下
根據(jù)日志可以看到占了512m內(nèi)存,默認是8848端口
瀏覽器訪問本機8848,用戶名密碼默認都是nacos:http://192.168.0.109:8848/nacos/index.html


如上圖可以看到啟動成功,成功進入運維界面。
這樣啟動默認用的是nacos內(nèi)嵌的數(shù)據(jù)庫,也可以指定mysql數(shù)據(jù)庫,方便看數(shù)據(jù)。
配置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.
*/
/******************************************/
/* 數(shù)據(jù)庫全名 = 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 '創(chuàng)建時間',
`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';
/******************************************/
/* 數(shù)據(jù)庫全名 = 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 '內(nèi)容',
`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='增加租戶字段';
/******************************************/
/* 數(shù)據(jù)庫全名 = 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 '創(chuàng)建時間',
`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';
/******************************************/
/* 數(shù)據(jù)庫全名 = 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 '創(chuàng)建時間',
`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';
/******************************************/
/* 數(shù)據(jù)庫全名 = 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';
/******************************************/
/* 數(shù)據(jù)庫全名 = 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 '單個配置大小上限,單位為字節(jié),0表示使用默認值',
`max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大個數(shù),,0表示使用默認值',
`max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '單個聚合數(shù)據(jù)的子配置大小上限,單位為字節(jié),0表示使用默認值',
`max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大變更歷史數(shù)量',
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時間',
`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容量信息表';
/******************************************/
/* 數(shù)據(jù)庫全名 = 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='多租戶改造';
/******************************************/
/* 數(shù)據(jù)庫全名 = 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 '單個配置大小上限,單位為字節(jié),0表示使用默認值',
`max_aggr_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '聚合子配置最大個數(shù)',
`max_aggr_size` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '單個聚合數(shù)據(jù)的子配置大小上限,單位為字節(jié),0表示使用默認值',
`max_history_count` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '最大變更歷史數(shù)量',
`gmt_create` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時間',
`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 '創(chuàng)建時間',
`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創(chuàng)建nacos_config庫,導(dǎo)入conf下nacos-mysql.sql文件
創(chuàng)建后如圖:

修改application.properties中連接數(shù)據(jù)庫信息,將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開發(fā)環(huán)境命名空間,新建之后會自動生成一個命名空間id。

在dev命名空間下新建如下配置(剛好這個配置和springboot項目spring.application.name是一樣的):

引入以下三個依賴包
spring-cloud-starter-alibaba-nacos-config 配置中心
spring-cloud-starter-alibaba-nacos-discovery注冊中心
nacos-client 客戶端(如果服務(wù)里不編寫自動發(fā)布腳本,這個引不引都沒關(guān)系)
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
# 公共的配置,刷新默認關(guān)閉
extension-configs:
- data-id: application.yaml
group: MY_GROUP
- data-id: RocketMQ.yaml
group: MY_GROUP
# 命名空間ID(隔離不同的環(huán)境)
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
# 默認的注冊服務(wù)組
group: DEFAULT_GROUP
# 服務(wù)注冊命名空間ID(隔離不同的環(huán)境)
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應(yīng)用上下文環(huán)境
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服務(wù)列表也能看到上線的服務(wù)了:

nacos集群
在三臺機子上分別部署nacos,在nacos的解壓目錄nacos/的conf目錄下,有配置文件cluster.conf.example,需要自行復(fù)制一份,修改名稱為cluster.conf,每行配置成ip:port。(配置3個或3個以上節(jié)點)
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
會發(fā)現(xiàn)三臺都啟動成功了。
集群管理下的節(jié)點列表出現(xiàn)了三個地址。
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的格式)
但是這樣的配置方式在實際使用上可能會比較麻煩,因為生產(chǎn)環(huán)境中的微服務(wù)往往有很多個,如果以后加nacos服務(wù)器,那這么多的微服務(wù)都要更改一遍嗎,還可以用nginx轉(zhuǎn)發(fā)到集群節(jié)點,這樣springboot中只要配置一個nginx固定地址就好了,加機器只要統(tǒng)一更改nginx上的轉(zhuǎn)發(fā)路徑就可以了。
注意:集群模式下要用真機,不要用改端口的偽集群了,除了8848端口外,即便是改了不同的端口,啟動的時候還是會報其他端口占用,三臺不同機子的成功率大一點。
參考:https://blog.csdn.net/qq_32352777/article/details/86560333
http://www.itdecent.cn/p/4b5d10bdf923
======20240523更新====
安裝2.2.3版本時遇到點問題,記錄一下。
nacos從2.2.2開始,默認不啟用登錄界面,鑒權(quán)描述如下:
https://nacos.io/zh-cn/docs/v2/guide/user/auth.html
2.2.2版本之前的Nacos默認控制臺,無論服務(wù)端是否開啟鑒權(quán),都會存在一個登錄頁;這導(dǎo)致很多用戶被誤導(dǎo)認為Nacos默認是存在鑒權(quán)的。在社區(qū)安全工程師的建議下,Nacos自2.2.2版本開始,在未開啟鑒權(quán)時,默認控制臺將不需要登錄即可訪問,同時在控制臺中給予提示,提醒用戶當前集群未開啟鑒權(quán)。
在用戶開啟鑒權(quán)后,控制臺才需要進行登錄訪問。
參考如下鏈接解決了這個問題:
https://blog.csdn.net/qfyh_djh/article/details/137006862
修改application.properties里的
#開啟鑒權(quán)
nacos.core.auth.enabled=true
#關(guān)閉使用 user-agent 判斷服務(wù)端請求并放行鑒權(quán)的功能
nacos.core.auth.enable.userAgentAuthWhite=false
#權(quán)限緩存開關(guān),開啟后權(quán)限緩存的更新默認有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編碼,否則無法啟動節(jié)點。
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;
}
}