SpringCloud集成Nacos的使用小结
程序员文章站
2022-06-24 22:26:00
nacos 注册中心nacos 是 dubbo 生态系统中重要的注册中心实现,其中 dubbo-registry-nacos 则是 dubbo 融合 nacos 注册中心的实现。nacos服务安装与启...
nacos 注册中心
nacos 是 dubbo 生态系统中重要的注册中心实现,其中 dubbo-registry-nacos 则是 dubbo 融合 nacos 注册中心的实现。
nacos服务安装与启动
安装地址:
- 本文在windows环境测试,下载zip版,解压。
- 配置conf目录下的application.properties文件,配置nacos数据源,端口等。
#*************** spring boot related configurations ***************# ### default web context path: server.servlet.contextpath=/nacos ### default web server port: server.port=8848 #*************** network related configurations ***************# ### if prefer hostname over ip for nacos server addresses in cluster.conf: # nacos.inetutils.prefer-hostname-over-ip=false ### specify local server's ip: # nacos.inetutils.ip-address= #*************** config module related configurations ***************# ### if user mysql as datasource: spring.datasource.platform=mysql ### count of db: db.num=1 ### connect url of db: db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?servertimezone=utc&characterencoding=utf8 db.user=root db.password=123456 #*************** naming module related configurations ***************# ### data dispatch task execution period in milliseconds: # nacos.naming.distro.taskdispatchperiod=200 ### data count of batch sync task: # nacos.naming.distro.batchsynckeycount=1000 ### retry delay in milliseconds if sync task failed: # nacos.naming.distro.syncretrydelay=5000
初始化数据库,脚本位于conf目录下nacos-mysql.sql
启动nacos服务,在cmd中执行bin目录下startup.cmd:
d:\>cd nacos/bin d:\nacos\bin>startup.cmd ,--. ,--.'| ,--,: : | nacos 1.2.1 ,`--.'`| ' : ,---. running in stand alone mode, all function modules | : : | | ' ,'\ .--.--. port: 8848 : | \ | : ,--.--. ,---. / / | / / ' pid: 20700 | : ' '; | / \ / \. ; ,. :| : /`./ console: http://10.118.37.75:8848/nacos/index.html ' ' ;. ;.--. .-. | / / '' | |: :| : ;_ | | | \ | \__\/: . .. ' / ' | .; : \ \ `. https://nacos.io ' : | ; .' ," .--.; |' ; :__| : | `----. \ | | '`--' / / ,. |' | '.'|\ \ / / /`--' / ' : | ; : .' \ : : `----' '--'. / ; |.' | , .-./\ \ / `--'---' '---' `--`---' `----' 2020-05-07 16:09:06,639 info bean 'org.springframework.security.config.annotation.configuration.objectpostprocessorconfiguration' of type [org.springframework.security.config.annotation.configuration.objectpostprocessorconfiguration$$enhancerbyspringcglib$$d2a494f3] is not eligible for getting processed by all beanpostprocessors (for example: not eligible for auto-proxying) 2020-05-07 16:09:06,713 info bean 'objectpostprocessor' of type [org.springframework.security.config.annotation.configuration.autowirebeanfactoryobjectpostprocessor] is not eligible for getting processed by all beanpostprocessors (for example: not eligible for auto-proxying) 2020-05-07 16:09:06,715 info bean 'org.springframework.security.access.expression.method.defaultmethodsecurityexpressionhandler@2de56eb2' 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) 2020-05-07 16:09:06,717 info bean 'org.springframework.security.config.annotation.method.configuration.globalmethodsecurityconfiguration' of type [org.springframework.security.config.annotation.method.configuration.globalmethodsecurityconfiguration$$enhancerbyspringcglib$$f77937a5] is not eligible for getting processed by all beanpostprocessors (for example: not eligible for auto-proxying) 2020-05-07 16:09:06,721 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) 2020-05-07 16:09:07,176 info tomcat initialized with port(s): 8848 (http) 2020-05-07 16:09:07,280 info root webapplicationcontext: initialization completed in 2308 ms 2020-05-07 16:09:16,998 info initializing executorservice 'applicationtaskexecutor' 2020-05-07 16:09:17,138 info adding welcome page: class path resource [static/index.html] 2020-05-07 16:09:17,390 info creating filter chain: ant [pattern='/**'], [] 2020-05-07 16:09:17,418 info creating filter chain: any request, [org.springframework.security.web.context.request.async.webasyncmanagerintegrationfilter@163d04ff, org.springframework.security.web.context.securitycontextpersistencefilter@1698fc68, org.springframework.security.web.header.headerwriterfilter@56a4479a, org.springframework.security.web.csrf.csrffilter@565b064f, org.springframework.security.web.authentication.logout.logoutfilter@53d1b9b3, org.springframework.security.web.savedrequest.requestcacheawarefilter@207b8649, org.springframework.security.web.servletapi.securitycontextholderawarerequestfilter@57eda880, org.springframework.security.web.authentication.anonymousauthenticationfilter@7c209437, org.springframework.security.web.session.sessionmanagementfilter@20a8a64e, org.springframework.security.web.access.exceptiontranslationfilter@73163d48] 2020-05-07 16:09:17,502 info exposing 2 endpoint(s) beneath base path '/actuator' 2020-05-07 16:09:17,528 info initializing executorservice 'taskscheduler' 2020-05-07 16:09:17,639 info tomcat started on port(s): 8848 (http) with context path '/nacos' 2020-05-07 16:09:17,645 info nacos logs files: d:\nacos\logs\ 2020-05-07 16:09:17,646 info nacos conf files: d:\nacos\conf\ 2020-05-07 16:09:17,646 info nacos data files: d:\nacos\data\ 2020-05-07 16:09:17,646 info nacos started successfully in stand alone mode. 2020-05-07 16:09:17,851 info initializing servlet 'dispatcherservlet' 2020-05-07 16:09:17,858 info completed initialization in 6 ms
nacos平台
访问路径:http://localhost:8848/nacos
可以新建多个环境,项目中通过命名空间映射相应的环境配置
spring: profiles: active: dev datasource: driverclassname: com.mysql.cj.jdbc.driver jdbc-url: jdbc:mysql://106.13.181.6:3306/demo username: root password: 123456
新增配置后发布
springcloud项目配置
依赖配置
<dependency> <groupid>com.alibaba.cloud</groupid> <artifactid>spring-cloud-starter-alibaba-nacos-discovery</artifactid> <version>2.1.1.release</version> </dependency> <dependency> <groupid>com.alibaba.cloud</groupid> <artifactid>spring-cloud-starter-alibaba-nacos-config</artifactid> <version>2.1.1.release</version> </dependency>
通过bootstrap.yml配置启动,bootstrap-dev.yml配置文件如下:
spring: application: name: demo cloud: nacos: server-addr: 127.0.0.1:8848 config: namespace: 9c6b8156-d045-463d-8fe6-4658ce78d0cc file-extension: yml
启动类配置
package com.example.demo; import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.cloud.client.discovery.enablediscoveryclient; @springbootapplication @enablediscoveryclient public class demoapplication { public static void main(string[] args) { springapplication.run(demoapplication.class, args); } }
数据源配置
package com.example.demo.config; import com.baomidou.mybatisplus.extension.plugins.paginationinterceptor; import com.baomidou.mybatisplus.extension.spring.mybatissqlsessionfactorybean; import org.apache.ibatis.plugin.interceptor; import org.mybatis.spring.mapper.mapperscannerconfigurer; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.beans.factory.annotation.qualifier; import org.springframework.boot.context.properties.configurationproperties; import org.springframework.boot.jdbc.datasourcebuilder; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.core.io.support.pathmatchingresourcepatternresolver; import javax.sql.datasource; @configuration public class sqlsessionconfig { private logger logger = loggerfactory.getlogger(sqlsessionconfig.class); @bean("datasource") @configurationproperties(prefix="spring.datasource") public datasource masterdatasource() { return datasourcebuilder.create().build(); } @bean("mysqlsessionfactorybean") public mybatissqlsessionfactorybean createsqlsessionfactory(@qualifier("datasource") datasource datasource, @qualifier("paginationinterceptor") paginationinterceptor paginationinterceptor) { // mybatissqlsessionfactory mybatissqlsessionfactorybean sqlsessionfactorybean = null; try { // 实例sessionfactory sqlsessionfactorybean = new mybatissqlsessionfactorybean(); // 配置数据源 sqlsessionfactorybean.setdatasource(datasource); // 设置 mybatis-plus 分页插件 interceptor [] plugins = {paginationinterceptor}; sqlsessionfactorybean.setplugins(plugins); // 加载mybatis配置文件 pathmatchingresourcepatternresolver resourcepatternresolver = new pathmatchingresourcepatternresolver(); sqlsessionfactorybean.setmapperlocations(resourcepatternresolver.getresources("classpath*:mapper/*.xml")); } catch (exception e) { logger.error("创建sqlsession连接工厂错误:{}", e.getmessage()); } return sqlsessionfactorybean; } @bean public mapperscannerconfigurer mygetmapperscannerconfigurer() { mapperscannerconfigurer mymapperscannerconfigurer = new mapperscannerconfigurer(); mymapperscannerconfigurer.setbasepackage("com.example.demo.mapper"); mymapperscannerconfigurer.setsqlsessionfactorybeanname("mysqlsessionfactorybean"); return mymapperscannerconfigurer; } }
controller
package com.example.demo.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.page; import com.example.demo.bean.userdto; import com.example.demo.constants.sexenum; import com.example.demo.entity.user; import com.example.demo.service.userservice; import org.springframework.beans.factory.annotation.autowired; import org.springframework.web.bind.annotation.requestbody; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.restcontroller; import java.time.localdatetime; import java.util.list; @restcontroller @requestmapping(value = "/demo") public class usercontroller { @autowired private userservice userservice; @requestmapping(value = "/create", method = requestmethod.post) public string create(@requestbody userdto userdto){ user user = new user(); user.setname(userdto.getname()); user.setphone(userdto.getphone()); user.setcreatetime(localdatetime.now()); user.setenable(true); user.setversion(1l); user.setsex(sexenum.getsexenum(userdto.getsex())); userservice.insert(user); return "ok"; } }
启动项目
2020-05-08 15:37:26.384 info 12544 --- [ main] trationdelegate$beanpostprocessorchecker : bean 'org.springframework.cloud.autoconfigure.configurationpropertiesrebinderautoconfiguration' of type [org.springframework.cloud.autoconfigure.configurationpropertiesrebinderautoconfiguration$$enhancerbyspringcglib$$9ea5255e] is not eligible for getting processed by all beanpostprocessors (for example: not eligible for auto-proxying) . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: spring boot :: (v2.2.6.release) 2020-05-08 15:37:26.601 info 12544 --- [ main] c.a.c.n.c.nacospropertysourcebuilder : loading nacos data, dataid: 'demo', group: 'default_group', data: spring: profiles: active: dev datasource: driverclassname: com.mysql.cj.jdbc.driver jdbc-url: jdbc:mysql://106.13.181.6:3306/demo username: root password: 123456 2020-05-08 15:37:26.608 warn 12544 --- [ main] c.a.c.n.c.nacospropertysourcebuilder : ignore the empty nacos configuration and get it based on dataid[demo.yml] & group[default_group] 2020-05-08 15:37:26.612 warn 12544 --- [ main] c.a.c.n.c.nacospropertysourcebuilder : ignore the empty nacos configuration and get it based on dataid[demo-dev.yml] & group[default_group] 2020-05-08 15:37:26.612 info 12544 --- [ main] b.c.propertysourcebootstrapconfiguration : located property source: compositepropertysource {name='nacos', propertysources=[nacospropertysource {name='demo-dev.yml'}, nacospropertysource {name='demo.yml'}, nacospropertysource {name='demo'}]} 2020-05-08 15:37:26.616 info 12544 --- [ main] com.example.demo.demoapplication : the following profiles are active: dev 2020-05-08 15:37:26.984 warn 12544 --- [ main] o.m.s.mapper.classpathmapperscanner : skipping mapperfactorybean with name 'usermapper' and 'com.example.demo.mapper.usermapper' mapperinterface. bean already defined with the same name! 2020-05-08 15:37:26.984 warn 12544 --- [ main] o.m.s.mapper.classpathmapperscanner : no mybatis mapper was found in '[com.example.demo.mapper]' package. please check your configuration. 2020-05-08 15:37:26.985 info 12544 --- [ main] o.s.c.a.configurationclasspostprocessor : cannot enhance @configuration bean definition 'sqlsessionconfig' since its singleton instance has been created too early. the typical cause is a non-static @bean method with a beandefinitionregistrypostprocessor return type: consider declaring such methods as 'static'. 2020-05-08 15:37:27.004 info 12544 --- [ main] o.s.cloud.context.scope.genericscope : beanfactory id=118dc0e1-e30f-3c3e-b857-cf20ba8b4123 2020-05-08 15:37:27.131 info 12544 --- [ main] trationdelegate$beanpostprocessorchecker : bean 'org.springframework.cloud.autoconfigure.configurationpropertiesrebinderautoconfiguration' of type [org.springframework.cloud.autoconfigure.configurationpropertiesrebinderautoconfiguration$$enhancerbyspringcglib$$9ea5255e] is not eligible for getting processed by all beanpostprocessors (for example: not eligible for auto-proxying) 2020-05-08 15:37:27.302 info 12544 --- [ main] o.s.b.w.embedded.tomcat.tomcatwebserver : tomcat initialized with port(s): 8080 (http) 2020-05-08 15:37:27.309 info 12544 --- [ main] o.a.coyote.http11.http11nioprotocol : initializing protocolhandler ["http-nio-8080"] 2020-05-08 15:37:27.309 info 12544 --- [ main] o.apache.catalina.core.standardservice : starting service [tomcat] 2020-05-08 15:37:27.309 info 12544 --- [ main] org.apache.catalina.core.standardengine : starting servlet engine: [apache tomcat/9.0.33] 2020-05-08 15:37:27.434 info 12544 --- [ main] o.a.c.c.c.[tomcat].[localhost].[/] : initializing spring embedded webapplicationcontext 2020-05-08 15:37:27.435 info 12544 --- [ main] o.s.web.context.contextloader : root webapplicationcontext: initialization completed in 810 ms _ _ |_ _ _|_. ___ _ | _ | | |\/|_)(_| | |_\ |_)||_|_\ / | 3.3.1 2020-05-08 15:37:27.822 warn 12544 --- [ main] c.n.c.sources.urlconfigurationsource : no urls will be polled as dynamic configuration sources. 2020-05-08 15:37:27.823 info 12544 --- [ main] c.n.c.sources.urlconfigurationsource : to enable urls as dynamic configuration sources, define system property archaius.configurationsource.additionalurls or make config.properties available on classpath. 2020-05-08 15:37:27.825 warn 12544 --- [ main] c.n.c.sources.urlconfigurationsource : no urls will be polled as dynamic configuration sources. 2020-05-08 15:37:27.826 info 12544 --- [ main] c.n.c.sources.urlconfigurationsource : to enable urls as dynamic configuration sources, define system property archaius.configurationsource.additionalurls or make config.properties available on classpath. 2020-05-08 15:37:27.951 info 12544 --- [ main] o.s.s.concurrent.threadpooltaskexecutor : initializing executorservice 'applicationtaskexecutor' 2020-05-08 15:37:28.151 info 12544 --- [ main] o.s.s.c.threadpooltaskscheduler : initializing executorservice 2020-05-08 15:37:28.391 info 12544 --- [ main] o.a.coyote.http11.http11nioprotocol : starting protocolhandler ["http-nio-8080"] 2020-05-08 15:37:28.409 info 12544 --- [ main] o.s.b.w.embedded.tomcat.tomcatwebserver : tomcat started on port(s): 8080 (http) with context path '' 2020-05-08 15:37:28.549 info 12544 --- [ main] c.a.c.n.registry.nacosserviceregistry : nacos registry, default_group demo 10.118.37.75:8080 register finished 2020-05-08 15:37:28.618 info 12544 --- [ main] com.example.demo.demoapplication : started demoapplication in 2.941 seconds (jvm running for 3.791) 2020-05-08 15:37:33.589 info 12544 --- [nio-8080-exec-2] o.a.c.c.c.[tomcat].[localhost].[/] : initializing spring dispatcherservlet 'dispatcherservlet' 2020-05-08 15:37:33.590 info 12544 --- [nio-8080-exec-2] o.s.web.servlet.dispatcherservlet : initializing servlet 'dispatcherservlet' 2020-05-08 15:37:33.597 info 12544 --- [nio-8080-exec-2] o.s.web.servlet.dispatcherservlet : completed initialization in 5 ms 2020-05-08 15:37:33.663 info 12544 --- [nio-8080-exec-2] com.example.demo.config.logaspect :
测试
2020-05-08 16:05:13.994 info 12544 --- [nio-8080-exec-4] com.example.demo.config.logaspect : 请求信息: 【请求地址】:/demo/create 【请求头】:content-type = application/json, user-agent = postmanruntime/7.24.0, accept = */*, postman-token = fc010815-8e7b-4e11-9fed-3d061f388faf, host = localhost:8080, accept-encoding = gzip, deflate, br, connection = keep-alive, content-length = 49 【请求方法】:string com.example.demo.controller.usercontroller.create(userdto) 【请求参数】:[userdto(id=null, name=zhangsan, phone=17751033130, sex=1)] 2020-05-08 16:05:14.004 warn 12544 --- [nio-8080-exec-4] com.zaxxer.hikari.pool.poolbase : hikaripool-1 - failed to validate connection com.mysql.cj.jdbc.connectionimpl@2bacd020 (no operations allowed after connection closed.). possibly consider using a shorter maxlifetime value. 2020-05-08 16:05:14.008 warn 12544 --- [nio-8080-exec-4] com.zaxxer.hikari.pool.poolbase : hikaripool-1 - failed to validate connection com.mysql.cj.jdbc.connectionimpl@5283f4ad (no operations allowed after connection closed.). possibly consider using a shorter maxlifetime value. 2020-05-08 16:05:14.009 warn 12544 --- [nio-8080-exec-4] com.zaxxer.hikari.pool.poolbase : hikaripool-1 - failed to validate connection com.mysql.cj.jdbc.connectionimpl@1fe3130d (no operations allowed after connection closed.). possibly consider using a shorter maxlifetime value. 2020-05-08 16:05:14.010 warn 12544 --- [nio-8080-exec-4] com.zaxxer.hikari.pool.poolbase : hikaripool-1 - failed to validate connection com.mysql.cj.jdbc.connectionimpl@11977567 (no operations allowed after connection closed.). possibly consider using a shorter maxlifetime value. 2020-05-08 16:05:14.011 warn 12544 --- [nio-8080-exec-4] com.zaxxer.hikari.pool.poolbase : hikaripool-1 - failed to validate connection com.mysql.cj.jdbc.connectionimpl@641256c2 (no operations allowed after connection closed.). possibly consider using a shorter maxlifetime value. 2020-05-08 16:05:14.013 warn 12544 --- [nio-8080-exec-4] com.zaxxer.hikari.pool.poolbase : hikaripool-1 - failed to validate connection com.mysql.cj.jdbc.connectionimpl@29f9f071 (no operations allowed after connection closed.). possibly consider using a shorter maxlifetime value. 2020-05-08 16:05:14.015 warn 12544 --- [nio-8080-exec-4] com.zaxxer.hikari.pool.poolbase : hikaripool-1 - failed to validate connection com.mysql.cj.jdbc.connectionimpl@2e05f538 (no operations allowed after connection closed.). possibly consider using a shorter maxlifetime value. 2020-05-08 16:05:14.016 warn 12544 --- [nio-8080-exec-4] com.zaxxer.hikari.pool.poolbase : hikaripool-1 - failed to validate connection com.mysql.cj.jdbc.connectionimpl@41391d2 (no operations allowed after connection closed.). possibly consider using a shorter maxlifetime value. 2020-05-08 16:05:14.017 warn 12544 --- [nio-8080-exec-4] com.zaxxer.hikari.pool.poolbase : hikaripool-1 - failed to validate connection com.mysql.cj.jdbc.connectionimpl@72c163d4 (no operations allowed after connection closed.). possibly consider using a shorter maxlifetime value. 2020-05-08 16:05:14.019 warn 12544 --- [nio-8080-exec-4] com.zaxxer.hikari.pool.poolbase : hikaripool-1 - failed to validate connection com.mysql.cj.jdbc.connectionimpl@145d7f85 (no operations allowed after connection closed.). possibly consider using a shorter maxlifetime value. 2020-05-08 16:05:14.545 debug 12544 --- [nio-8080-exec-4] c.example.demo.mapper.usermapper.insert : ==> preparing: insert into user ( name, sex, phone, create_time, enable, version ) values ( ?, ?, ?, ?, ?, ? ) 2020-05-08 16:05:14.548 debug 12544 --- [nio-8080-exec-4] c.example.demo.mapper.usermapper.insert : ==> parameters: zhangsan(string), man(string), 17751033130(string), 2020-05-08t16:05:13.995(localdatetime), true(boolean), 1(long) 2020-05-08 16:05:14.686 debug 12544 --- [nio-8080-exec-4] c.example.demo.mapper.usermapper.insert : <== updates: 1 2020-05-08 16:05:14.697 info 12544 --- [nio-8080-exec-4] com.example.demo.config.logaspect : 执行结果: 【响应结果】:"ok" 【执行耗时】:701毫秒
到此这篇关于springcloud集成nacos的使用小结的文章就介绍到这了,更多相关springcloud集成nacos内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!