Spring Cloud Alibaba之服务治理Nacos
Spring Cloud Alibaba之服务治理Nacos
- Spring Cloud Alibaba版本依赖
- Nacos概述
- 搭建Nacos Server
- 服务注册
- 注册user-center服务
- 添加依赖
- 配置nacos
- 开启服务注册与发现
- 启动服务
- 查看服务是否注册
- 注册pay-center服务
- 添加依赖
- 配置nacos
- 开启服务注册与发现
- 启动日志
- 查看服务是否注册
- 服务发现
- 添加测试接口
- 执行测试
- 服务调用
- 提供服务
- 消费服务
- 执行测试
- Nacos Config配置中心
- 添加依赖
- 创建bootstrap.yml
- Nacos控制台新建配置
- 执行测试
- 配置动态刷新
- 配置共享
- 同服务不同环境间共享配置
- 不同服务间共享配置
Spring Cloud Alibaba版本依赖
添加SpringBoot、SpringCloud、SpringCloudAlibaba版本依赖整合,在dependencyManagement添加核心依赖,在dependencies添加需使用的依赖
spring-cloud-alibaba版本说明: https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.2.RELEASE</version><relativePath/></parent><dependencyManagement><dependencies><!--整合spring cloud--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Hoxton.SR9</version><type>pom</type><scope>import</scope></dependency><!--整合spring cloud alibaba--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>2.2.6.RELEASE</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
Nacos概述
Nacos提供了一组简单易用的特性集,能快速实现动态服务发现、服务配置、服务元数据及流量管理。
Nacos文档: https://nacos.io/zh-cn/docs/quick-start.html
Nacos地图
Nacos生态图
使用Nacos简化服务发现、配置管理、服务治理及管理的解决方案,让微服务的发现、管理、共享、组合更加容易。
搭建Nacos Server
下载Nacos
首先确定spring-cloud-alibaba对应Nacos版本
<!--点击artifactId进入spring-cloud-alibaba依赖管理中查看nacos的版本--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-dependencies</artifactId><version>2.2.6.RELEASE</version><type>pom</type><scope>import</scope></dependency><nacos.client.version>1.4.2</nacos.client.version>
Nacos下载对应版本:https://github.com/alibaba/nacos/releases
Windows
启动命令(standalone代表着单机模式运行,非集群模式):
startup.cmd -m standalone
关闭服务器
shutdown.cmd
Docker部署单机Nacos
https://blog.csdn.net/qq_38628046/article/details/106875278
服务注册
注册user-center服务
添加依赖
<!--nacos客户端--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency>
配置nacos
spring:application:name: user-centercloud:nacos:discovery:# 指定nacos server的地址server-addr: IP:8848# 指定namespace,nacos的Web界面创建命名空间,使用生产或指定的命名空间ID,类似分组,不同服务划分到不同的组里面# namespace: 54c13a17-6ef8-4f7d-8c4a-2f69ae06c13c# ShangHai# 指定集群名称(如以城市、地区划分)cluster-name: ShangHai# 元数据信息metadata:instance: userversion: 0.0.1
开启服务注册与发现
@EnableDiscoveryClient 开启服务注册发现功能
@SpringBootApplication
@EnableDiscoveryClient
public class UserApplication {public static void main(String[] args) {SpringApplication.run(UserApplication.class, args);}
}
启动服务
INFO 10312 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 18 endpoint(s) beneath base path '/actuator'INFO 10312 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''INFO 10312 --- [ main] c.a.c.n.registry.NacosServiceRegistry : nacos registry, DEFAULT_GROUP user-center 192.168.179.1:8081 register finished
查看服务是否注册
使用命名空间
服务详情
注册pay-center服务
添加依赖
<!--nacos客户端--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency>
配置nacos
spring:application:name: pay-centercloud:nacos:discovery:server-addr: IP:8848cluster-name: BeiJing# namespace: 54c13a17-6ef8-4f7d-8c4a-2f69ae06c13cmetadata:instance: payversion: 0.0.1
开启服务注册与发现
@EnableDiscoveryClient 开启服务注册发现功能
@SpringBootApplication
@EnableDiscoveryClient
public class PayApplication {public static void main(String[] args) {SpringApplication.run(PayApplication.class, args);}
}
启动日志
INFO 15440 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 19 endpoint(s) beneath base path '/actuator'INFO 15440 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8082 (http) with context path ''INFO 15440 --- [ main] o.s.cloud.commons.util.InetUtils : Cannot determine local hostnameINFO 15440 --- [ main] c.a.c.n.registry.NacosServiceRegistry : nacos registry, DEFAULT_GROUP pay-center 192.168.179.1:8082 register finished
查看服务是否注册
服务详情
服务发现
添加测试接口
在pay-center服务中添加test接口
@Slf4j
@RestController
public class TestController {@Autowired// DiscoveryClient是专门负责服务注册和发现的,可以通过它获取到注册到注册中心的所有服务private DiscoveryClient discoveryClient;/*** 服务发现,从服务中心获取指定服务实例** @return 用户中心所有实例的地址信息*/@GetMapping("test")public List<ServiceInstance> getInstances() {// 查询指定服务的所有实例的信息return this.discoveryClient.getInstances("user-center");}
}
执行测试
重启项目,访问:http://192.168.179.1:8082/test
[{"serviceId": "user-center","host": "192.168.179.1","port": 8081,"secure": false,"metadata": {"instance": "user","nacos.instanceId": "192.168.179.1#8081#ShangHai#DEFAULT_GROUP@@user-center","nacos.weight": "1.0","nacos.cluster": "ShangHai","nacos.ephemeral": "true","nacos.healthy": "true","preserved.register.source": "SPRING_CLOUD","version": "0.0.1"},"uri": "http://192.168.179.1:8081","scheme": null,"instanceId": null}
]
当停止用户中心,再获取服务实例地址
[]
启动user-center服务后,再修改服务端口启动第二个user-center服务
-Dserver.port=8083
启动日志
INFO 12292 --- [ main] o.s.b.a.e.web.EndpointLinksResolver : Exposing 18 endpoint(s) beneath base path '/actuator'INFO 12292 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8083 (http) with context path ''INFO 12292 --- [ main] c.a.c.n.registry.NacosServiceRegistry : nacos registry, DEFAULT_GROUP user-center 192.168.179.1:8083 register finished
查看服务是否注册
服务详情
再获取服务实例地址
[{"serviceId": "user-center","host": "192.168.179.1","port": 8083,"secure": false,"metadata": {"instance": "user","nacos.instanceId": "192.168.179.1#8083#ShangHai#DEFAULT_GROUP@@user-center","nacos.weight": "1.0","nacos.cluster": "ShangHai","nacos.ephemeral": "true","nacos.healthy": "true","preserved.register.source": "SPRING_CLOUD","version": "0.0.1"},"uri": "http://192.168.179.1:8083","scheme": null,"instanceId": null},{"serviceId": "user-center","host": "192.168.179.1","port": 8081,"secure": false,"metadata": {"instance": "user","nacos.instanceId": "192.168.179.1#8081#ShangHai#DEFAULT_GROUP@@user-center","nacos.weight": "1.0","nacos.cluster": "ShangHai","nacos.ephemeral": "true","nacos.healthy": "true","preserved.register.source": "SPRING_CLOUD","version": "0.0.1"},"uri": "http://192.168.179.1:8081","scheme": null,"instanceId": null}
]
服务调用
提供服务
在user-center服务中提供服务
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {private final UserService userService;@GetMapping("/selectUserById/{id}")@CheckLoginpublic User selectUserById(@PathVariable Integer id) {return this.userService.findById(id);}
}
消费服务
创建RestTemplate
@Bean
public RestTemplate getRestTemplate() {return new RestTemplate();
}
在pay-center服务中添加调用服务
@Slf4j
@RestController
public class TestController {@Autowiredprivate RestTemplate restTemplate;@Autowired// DiscoveryClient是专门负责服务注册和发现的,可以通过它获取到注册到注册中心的所有服务private DiscoveryClient discoveryClient;/*** 服务发现,从服务中心获取指定服务实例** @return 用户中心所有实例的地址信息*/@GetMapping("test")public List<ServiceInstance> getInstances() {// 查询指定服务的所有实例的信息return this.discoveryClient.getInstances("user-center");}@GetMapping("test/{id}")public UserDTO selectUserById(@PathVariable Integer id) {List<ServiceInstance> instances = this.discoveryClient.getInstances("user-center");// 实现负载均衡// int index = new Random().nextInt(instances.size());// ServiceInstance serviceInstance = instances.get(index);String instanceUrl = instances.stream().map(instance -> instance.getUri().toString() + "/users/selectUserById/{id}").findFirst().orElseThrow(() -> new IllegalArgumentException("获取user-center实例失败,没有相关实例"));return this.restTemplate.getForObject(instanceUrl, UserDTO.class,id);}
}
执行测试
访问http://192.168.179.1:8082/test/1
{"userName": "小白","age": 20,"sex": "男",
}
Nacos Config配置中心
使用nacos作为配置中心,就是将nacos当做一个服务端,将各个微服务看成是客户端,将各个微服务的配置文件统一存放在nacos上,然后各个微服务从nacos上拉取配置。
添加依赖
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency>
创建bootstrap.yml
在微服务中添加nacos config的配置,不能使用原来的application.yml作为配置文件,而是新建一个bootstrap.yml作为配置文件
配置文件优先级(由高到低)
bootstrap.properties -> bootstrap.yml -> application.properties -> application.yml
spring:cloud:nacos:config:server-addr: IP:8848file-extension: yaml # 配置文件格式application:name: nacos-config-centerprofiles:active: dev # 环境标识
Nacos控制台新建配置
约定大于配置,需与bootstrap.yml配置文件中配置信息一致
Data ID依据配置文件各项配置信息组合 : nacos-config-center-dev.yaml
执行测试
添加测试接口
@RestController
public class TestController {@Value("${my.nacosConfig}")private String nacosConfig;@GetMapping("/testNacosConfig")public String testNacosConfig() {return nacosConfig;}
}
测试从配置中心获取配置
配置动态刷新
如果修改了配置,程序是无法读取到最新配置的,可以通过 Spring Cloud 原生注解 @RefreshScope 实现配置自动更新 。
@RestController
// 开启配置的动态刷新功能
@RefreshScope
public class TestController {@Value("${my.nacosConfig}")private String nacosConfig;@GetMapping("/testNacosConfig")public String testNacosConfig() {return nacosConfig;}
}
测试配置动态刷新,更新Nacos配置信息后再访问
my:nacosConfig: nacos-server-config-update
配置共享
当配置越来越多的时候,就会发现有很多配置是重复的,因此可以考虑将公共配置文件提取出来实现共享
同服务不同环境间共享配置
创建以spring.application.name
命名的配置文件,然后将所有环境的公共配置放在里面
spring:datasource:driver-class-name: com.mysql.jdbc.Driverusername: rootpassword: 123456url: jdbc:mysql://IP:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
创建名以spring.application.name-dev
命名的配置存放开发环境的配置
my:nacosConfig: dev
创建名以spring.application.name-test
命名的配置存放测试环境的配置
my:nacosConfig: test
配置bootstrap.yml
spring:cloud:nacos:config:server-addr: IP:8848file-extension: yaml # 配置文件格式namespace: 87a4700f-1dc1-430c-8a99-de98d9e8c55agroup: TEST_GROUPapplication:name: nacos-config-centerprofiles:active: dev # 环境标识
启动项目
INFO 55156 --- [ restartedMain] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-nacos-config-center-dev.yaml,TEST_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-nacos-config-center.yaml,TEST_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-nacos-config-center,TEST_GROUP'}]
INFO 55156 --- [ restartedMain] cn.ybzy.demo.Application : The following profiles are active: dev
执行测试
@RestController
@RefreshScope
public class TestController {@Value("${my.nacosConfig}")private String nacosConfig;@GetMapping("/testNacosConfig")public String testNacosConfig() {return nacosConfig;}
}
不同服务间共享配置
定义一个公共配置,然后在不同微服务的配置文件中引入即可。
在nacos中新建配置文件,定义一个DataID为service-common.yaml
的配置,用于所有微服务共享
spring:datasource:driver-class-name: com.mysql.jdbc.Driverusername: rootpassword: 123456url: jdbc:mysql://IP:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
修改spring.application.name
命名的配置文件
my:serverName: nacos-configserver:port: 7777
修改bootstrap.yaml
spring:cloud:nacos:config:server-addr: IP:8848file-extension: yaml # 配置文件格式namespace: 87a4700f-1dc1-430c-8a99-de98d9e8c55agroup: TEST_GROUPshared-configs[0]:dataId: service-common.yaml # 配置文件名refresh: true # 是否自动刷新group: TEST_GROUP # 分组名refresh-enabled: true # 刷新配置的主开关,它默认打开(true)application:name: nacos-config-centerprofiles:active: dev # 环境标识
启动项目
Located property source: [BootstrapPropertySource {name='bootstrapProperties-nacos-config-center-dev.yaml,TEST_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-nacos-config-center.yaml,TEST_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-nacos-config-center,TEST_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-service-common.yaml,TEST_GROUP'}]
INFO 48844 --- [ restartedMain] cn.ybzy.demo.Application : The following profiles are active: devINFO 48844 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 7777 (http)
INFO 48844 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
INFO 48844 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
执行测试
@RestController
@RefreshScope
public class TestController {@Value("${my.serverName}")private String serverName;@GetMapping("/test")public String testNacosConfig() {return serverName;}
}
修改配置中心文件内容
my:serverName: nacos-config-centerserver:port: 7777
INFO 48844 --- [99-de98d9e8c55a] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-nacos-config-center-dev.yaml,TEST_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-nacos-config-center.yaml,TEST_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-nacos-config-center,TEST_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-service-common.yaml,TEST_GROUP'}]
INFO 48844 --- [99-de98d9e8c55a] o.s.boot.SpringApplication : The following profiles are active: dev
Spring Cloud Alibaba之服务治理Nacos相关推荐
- Spring Cloud Alibaba 之 服务治理:Nacos 如何实现微服务服务治理
前文我们学习了通用的微服务架构应包含哪些组件以及 Spring Cloud Alibaba 生态中对应的技术实现,其中整个架构体系最核心的组件是服务注册中心 Alibaba Nacos.本讲我们就对 ...
- 防止内卷和被潜规则,Spring Cloud Alibaba微服务架构实战派(上下册)|35岁程序员那些事
目录 1 写书缘由 2 本书上册核心内容 2.1 Spring Cloud Alibaba基础实战 2.1.1 主要内容 2.1.2 MyBatis-Plus实现多租户架构的核心原理 2.2 分布式服 ...
- Spring Cloud Alibaba 基础教程:Nacos 生产级版本 0.8.0
Spring Cloud Alibaba 基础教程:Nacos 生产级版本 0.8.0 昨晚Nacos社区发布了第一个生产级版本:0.8.0.由于该版本除了Bug修复之外,还提供了几个生产管理非常重要 ...
- Spring Cloud Alibaba基础教程:Nacos配置的多环境管理
<Spring Cloud Alibaba基础教程>连载中,关注我一起学期!前情回顾: <使用Nacos实现服务注册与发现> <支持的几种服务消费方式> <使 ...
- Spring Cloud Alibaba基础教程:Nacos的数据持久化 1
前情回顾: <Spring Cloud Alibaba基础教程:使用Nacos实现服务注册与发现> <Spring Cloud Alibaba基础教程:支持的几种服务消费方式> ...
- 从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(三) (mini-cloud) 搭建认证服务(认证/资源分离版) oauth2.0 (中)
本文承接上文<从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(三) (mini-cloud) 搭建认证服务(认证/资源分离版) oauth2.0 (上)> ...
- Spring Cloud Alibaba 微服务开发实践
作者:禅与计算机程序设计艺术 1.简介 Spring Cloud Alibaba 是阿里巴巴开源的基于 Spring Cloud 的微服务框架.该项目从最初孵化到现在已经历经十多年的发展,得到了广泛的 ...
- 从0到1手把手搭建spring cloud alibaba 微服务大型应用框架(十五) swagger篇 : gateway 集成swagger 与 knife4j实现在线api文档并嵌入到自己项目内
背景 我们日常开发中基本都是协同开发的,当然极个别的项目整体前后端都是一个人开发的,当多人协作时,尤其是前后端人员协同开发时 必然会面临着前端需要了解后端api接口的情况,两个选择,提前设计好文档,然 ...
- Spring Cloud Alibaba | Sentinel: 服务限流高级篇
Spring Cloud Alibaba | Sentinel: 服务限流高级篇 Springboot: 2.1.6.RELEASE SpringCloud: Greenwich.SR1 如无特殊说明 ...
- Spring Cloud Alibaba教程:使用Nacos作为服务注册中心
点击上方"方志朋",选择"置顶公众号" 技术文章第一时间送达! 什么是Nacos? Nacos 致力于帮助您发现.配置和管理微服务.Nacos 提供了一组简单易 ...
最新文章
- OpenCV(项目)车牌识别4 -- 总结篇
- php绘图效率,对于PHP绘图技术的理解
- 【基础】华为设备默认路由和静态路由配置实战
- php什么是阵列,php – 功能阵列的替代方法?
- Spring Boot————静态方法如何调用Spring容器中的Bean
- php 多态有什么用,php面向对象多态的介绍与优势
- 详解Transition-based Dependency parser基于转移的依存句法解析器
- ckplayer html5直播rtmp,实现简单网页rtmp直播:nginx+ckplayer+linux
- python模拟登陆qq空间
- python识别文字坐标_python识别图片上的文字并返回文字在图片中的坐标
- 基于LSTM的沪深股票价格预测
- 创建glance镜像报错HTTP503
- 【JVM】运行时数据区介绍,程序计数器和虚拟机栈详解
- 奶粉的全球与中国市场2022-2028年:技术、参与者、趋势、市场规模及占有率研究报告
- 网络安全之文件包含漏洞总结
- 主板有电无法启动_电脑主板通电但是开不了机是什么原因?
- latex 学习使用记录(插图片,插表格,插公式,插参考文献)
- 15.2数据库(2):MySQL基本增删改查
- ➢ 微信公众号运营教程(一)申请一个微信公众号
- 如何用python开发app —— 前言