当前位置: 首页 > news >正文

SpringCloud Nacos配置中心

nacos配置使用有2种

一种是全局的,在应用启动的时候与applocation.properties合并成新的配置文件

一种是局部引用,并可以动态更新

使用流程以2023.0.3.3为例子

引入依赖

  <dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId><version>2023.0.3.3</version></dependency>

新版本与老版本有区别,新的不要求使用bootstrap.yml文件,直接在application配置文件添加即可

applocation.properties添加配置

spring.cloud.nacos.server-addr=http://192.168.68.238:8848
spring.config.import[0]=nacos:mysql?refreshEnabled=true

其中mysql在nacos中配置如下

系统启动会会先拉去nacos配置与本地配置合并

22:02:41.759 [main] INFO com.alibaba.nacos.common.ability.discover.NacosAbilityManagerHolder -- [AbilityControlManager] Successfully initialize AbilityControlManager.   ____          _            __ _ _/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/  ___)| |_)| | | | | || (_| |  ) ) ) )'  |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot ::                (v3.2.4)2025-07-22T22:02:43.442+08:00  INFO 5568 --- [demo1] [           main] org.example.demo1.Demo1Application       : Starting Demo1Application using Java 21.0.1 with PID 5568 (F:\java\test1\demo1\target\classes started by FRT in F:\java\test1\demo1)
2025-07-22T22:02:43.443+08:00  INFO 5568 --- [demo1] [           main] org.example.demo1.Demo1Application       : The following 1 profile is active: "dev"
2025-07-22T22:02:43.655+08:00  INFO 5568 --- [demo1] [           main] c.a.c.n.c.NacosConfigDataLoader          : [Nacos Config] Load config[dataId=mysql, group=DEFAULT_GROUP] success
2025-07-22T22:02:46.231+08:00  INFO 5568 --- [demo1] [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=79902dc9-ee9c-3928-bf51-f1ad48ed6e40
2025-07-22T22:02:46.692+08:00  WARN 5568 --- [demo1] [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration$DeferringLoadBalancerInterceptorConfig' of type [org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration$DeferringLoadBalancerInterceptorConfig] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). The currently created BeanPostProcessor [lbRestClientPostProcessor] is declared through a non-static factory method on that class; consider declaring it as static instead.
2025-07-22T22:02:46.698+08:00  WARN 5568 --- [demo1] [           main] trationDelegate$BeanPostProcessorChecker : Bean 'deferringLoadBalancerInterceptor' of type [org.springframework.cloud.client.loadbalancer.DeferringLoadBalancerInterceptor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [lbRestClientPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies.
2025-07-22T22:02:47.321+08:00  INFO 5568 --- [demo1] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2025-07-22T22:02:47.350+08:00  INFO 5568 --- [demo1] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2025-07-22T22:02:47.351+08:00  INFO 5568 --- [demo1] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.19]
2025-07-22T22:02:47.565+08:00  INFO 5568 --- [demo1] [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2025-07-22T22:02:47.568+08:00  INFO 5568 --- [demo1] [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3906 ms
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
Get /192.168.68.121 network interface 
Get network interface info: name:wireless_32768 (Intel(R) Centrino(R) Advanced-N 6205)
Initialization Sequence datacenterId:2 workerId:20_ _   |_  _ _|_. ___ _ |    _ 
| | |\/|_)(_| | |_\  |_)||_|_\ /               |         3.5.12 
2025-07-22T22:02:49.929+08:00  INFO 5568 --- [demo1] [           main] o.s.c.openfeign.FeignClientFactoryBean   : For 'demo1' URL not provided. Will try picking an instance via load-balancing.
2025-07-22T22:02:50.047+08:00  INFO 5568 --- [demo1] [           main] c.a.c.n.a.NacosAnnotationProcessor       : [Nacos Config] Listening config for annotation: dataId=test, group=DEFAULT_GROUP
2025-07-22T22:02:50.177+08:00  INFO 5568 --- [demo1] [           main] c.a.c.n.a.NacosAnnotationProcessor       : [Nacos Config] register demo1Application#filed#test listener on org.example.demo1.Demo1Application$$SpringCGLIB$$0@4bdef487 
2025-07-22T22:02:52.836+08:00  INFO 5568 --- [demo1] [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2025-07-22T22:02:52.898+08:00  INFO 5568 --- [demo1] [           main] m.e.s.MybatisPlusApplicationContextAware : Register ApplicationContext instances org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@3eda0aeb
2025-07-22T22:02:54.049+08:00  INFO 5568 --- [demo1] [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2025-07-22T22:02:54.088+08:00  WARN 5568 --- [demo1] [           main] iguration$LoadBalancerCaffeineWarnLogger : Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
2025-07-22T22:02:54.319+08:00  INFO 5568 --- [demo1] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path ''
2025-07-22T22:02:54.349+08:00  INFO 5568 --- [demo1] [           main] c.a.n.p.a.s.c.ClientAuthPluginManager    : [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.impl.NacosClientAuthServiceImpl success.
2025-07-22T22:02:54.349+08:00  INFO 5568 --- [demo1] [           main] c.a.n.p.a.s.c.ClientAuthPluginManager    : [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.ram.RamClientAuthServiceImpl success.
2025-07-22T22:02:54.421+08:00  INFO 5568 --- [demo1] [           main] c.a.c.n.registry.NacosServiceRegistry    : nacos registry, DEFAULT_GROUP demo1 192.168.56.1:8080 register finished
2025-07-22T22:02:55.431+08:00  INFO 5568 --- [demo1] [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2025-07-22T22:02:55.454+08:00  INFO 5568 --- [demo1] [           main] org.example.demo1.Demo1Application       : Started Demo1Application in 16.826 seconds (process running for 18.746)
2025-07-22T22:02:55.464+08:00  INFO 5568 --- [demo1] [           main] c.a.c.n.refresh.NacosContextRefresher    : [Nacos Config] Listening config: dataId=mysql, group=DEFAULT_GROUP
2025-07-22T22:03:08.769+08:00  INFO 5568 --- [demo1] [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2025-07-22T22:03:08.770+08:00  INFO 5568 --- [demo1] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2025-07-22T22:03:08.773+08:00  INFO 5568 --- [demo1] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 3 ms
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1d160d9c] was not registered for synchronization because synchronization is not active
2025-07-22T22:03:08.936+08:00  INFO 5568 --- [demo1] [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2025-07-22T22:03:09.339+08:00  INFO 5568 --- [demo1] [nio-8080-exec-1] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@adfbf37
2025-07-22T22:03:09.342+08:00  INFO 5568 --- [demo1] [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@718283189 wrapping com.mysql.cj.jdbc.ConnectionImpl@adfbf37] will not be managed by Spring
==>  Preparing: SELECT id,unionid,token,username,password,nick_name,phone,head_url,ring,register_time,last_login_time FROM app_user WHERE id=?
==> Parameters: 11(String)
<==    Columns: id, unionid, token, username, password, nick_name, phone, head_url, ring, register_time, last_login_time
<==        Row: 11, , Xdtk2sBFPpLMx5J0Qz-io1KmOn4UyIgC6cZDv87YwhGVejTN39uSRlHA, test, 
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1d160d9c]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@685b68c5] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1721535422 wrapping com.mysql.cj.jdbc.ConnectionImpl@adfbf37] will not be managed by Spring
==>  Preparing: SELECT id,unionid,token,username,password,nick_name,phone,head_url,ring,register_time,last_login_time FROM app_user WHERE id=?
==> Parameters: 11(String)
<==    Columns: id, unionid, token, username, password, nick_name, phone, head_url, ring, register_time, last_login_time
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@685b68c5]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@57cd7671] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1493861112 wrapping com.mysql.cj.jdbc.ConnectionImpl@adfbf37] will not be managed by Spring
==>  Preparing: SELECT id,unionid,token,username,password,nick_name,phone,head_url,ring,register_time,last_login_time FROM app_user WHERE id=?
==> Parameters: 11(String)
<==    Columns: id, unionid, token, username, password, nick_name, phone, head_url, ring, register_time, last_login_time
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@57cd7671]

在日志中提示Load config[dataId=mysql, group=DEFAULT_GROUP] success

并且原配置中无数据库配置,引用nacos后访问数据库成功

局部参数测试,随便定一个变量,使用注解@NacosConfig

 @NacosConfig(dataId = "test", group = "DEFAULT_GROUP", key = "test.t1")private String test;

test内容

默认test值为nacos中的test.t1 的值32432434244543535353,并且支持动态跟新,在nacos更新后程序无需重启test变量自动更新

@GetMapping("/test")public String test() {return test;}

写个测试方法访问http://localhost:8080/test测试成功!

http://www.lryc.cn/news/596705.html

相关文章:

  • 网易视觉算法面试30问全景精解
  • Python实例之画小猪佩奇
  • Java函数指南:从Function到BiFunction的深度解析
  • AI AgentLLM架构演进的大逻辑和小脉络
  • rocky9-zabbix简单部署
  • 第十一章 用Java实现JVM之异常处理
  • C++11--锁分析
  • 华为视觉算法面试30问全景精解
  • What Does “Directory of the Script Being Run” Mean?
  • final修饰符不可变的底层
  • SpringBoot PO VO BO POJO实战指南
  • Pycharm下载、安装及配置
  • 力扣 hot100 Day52
  • RabbitMQ03——面试题
  • 为什么要微调大语言模型
  • 论文笔记 | Beyond Pick-and-Place: Tackling Robotic Stacking of Diverse Shapes
  • 解决pip指令超时问题
  • 数据结构 堆(2)---堆的实现
  • LeetCode 热题100:42.接雨水
  • Unity UI的未来之路:从UGUI到UI Toolkit的架构演进与特性剖析(1)
  • 业务流逻辑如何搭建?为何橙武平台选用了 LogicFlow?​
  • day19 链表
  • 程序是如何生成的-以c语言为例
  • 信息学奥赛一本通 1553:【例 2】暗的连锁
  • 前端_CSS复习
  • 【React 入门系列】React 组件通讯与生命周期详解
  • 高可用架构模式——数据集群和数据分区
  • 单细胞转录组学+空间转录组的整合及思路
  • OneCode3.0 UI组件注解详解手册
  • 【vscode】vscode中python虚拟环境的创建