Spring Cloud Alibaba之服务治理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 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-center
cloud:
nacos:
discovery:
# 指定nacos server的地址
server-addr: IP:8848
# 指定namespace,nacos的Web界面创建命名空间,使用生产或指定的命名空间ID,类似分组,不同服务划分到不同的组里面
# namespace: 54c13a17-6ef8-4f7d-8c4a-2f69ae06c13c
# ShangHai
# 指定集群名称(如以城市、地区划分)
cluster-name: ShangHai
# 元数据信息
metadata:
instance: user
version: 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-center
cloud:
nacos:
discovery:
server-addr: IP:8848
cluster-name: BeiJing
# namespace: 54c13a17-6ef8-4f7d-8c4a-2f69ae06c13c
metadata:
instance: pay
version: 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 hostname
INFO 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}")
@CheckLogin
public 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 {
@Autowired
private 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:8848
file-extension: yaml # 配置文件格式
application:
name: nacos-config-center
profiles:
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.Driver
username: root
password: 123456
url: 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:8848
file-extension: yaml # 配置文件格式
namespace: 87a4700f-1dc1-430c-8a99-de98d9e8c55a
group: TEST_GROUP
application:
name: nacos-config-center
profiles:
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.Driver
username: root
password: 123456
url: jdbc:mysql://IP:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
修改spring.application.name
命名的配置文件
my:
serverName: nacos-config
server:
port: 7777
修改bootstrap.yaml
spring:
cloud:
nacos:
config:
server-addr: IP:8848
file-extension: yaml # 配置文件格式
namespace: 87a4700f-1dc1-430c-8a99-de98d9e8c55a
group: TEST_GROUP
shared-configs[0]:
dataId: service-common.yaml # 配置文件名
refresh: true # 是否自动刷新
group: TEST_GROUP # 分组名
refresh-enabled: true # 刷新配置的主开关,它默认打开(true)
application:
name: nacos-config-center
profiles:
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: dev
INFO 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-center
server:
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
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137007.html