当前位置: 首页 > 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.dtcms.com/a/291991.html

相关文章:

  • CentOS 8文件描述符耗尽检测与处理实战指南
  • Linux CentOS 虚拟机升级内核至4.x以上版本
  • 为何在 Vue 的 v-model 指令中不能使用可选链(Optional Chaining)?
  • AI-调查研究-35-咖啡价格战 味觉与消费体验差异:自制咖啡为何更“好喝”?
  • 【Practical Business English Oral Scene Interpretation】 No9~10
  • vue 用hbuilder打包apk后返回键不好使
  • importlib.import_module() 的用法与实战案例
  • 重构创作边界:川翔云电脑 - UE5云端超算引擎​
  • B端UI组件库重构:如何让开发效率提升40%的交互逻辑拆解
  • 拥抱区块链红利:机遇无限,风险暗涌
  • Python 绘制各类折线图全指南:从基础到进阶
  • MATLAB软件使用频繁,企业如何做到“少买多用”?
  • 互联网隐私的未来:Web3、区块链与神秘法宝
  • Function Modifier
  • 动漫短剧系统开发:构建下一代沉浸式娱乐平台的架构设计与技术突破
  • 使用qt编写上位机程序,出现串口死掉无法接受数据的bug
  • Kotlin 中的单例模式(Singleton)与对象声明
  • 力扣-链表相关题 持续更新中。。。。。。
  • 手写 防抖函数、节流函数
  • 【企业APP上架小米应用商店需要做的准备】(本示例为uniapp开发)
  • LLM评测框架Ragas:SQL指标(解决了Ollama推理框架不支持的问题)
  • oracle查询数据结构滤涉及的sql语句
  • 程序是如何生成的-以c语言为例
  • 行内元素垂直边距为何失效?
  • Vite:下一代前端构建工具的革命
  • 金仓数据库风云
  • 基于JAVA实现基于“obj--html--pdf” 的PDF格式文本生成
  • C语言第二章分支与循环(下)——猜数字游戏
  • 【深度解析】从AWS re_Invent 2025看云原生技术发展趋势
  • AWS RDS 排查性能问题