前言
本文会继续上篇文章,对SpringCloud Alibaba的组件做详细介绍,并对其使用方法做实例演示说明,本章主要是对SpringCloud Alibaba的组件Nacos(配置管理) 、Sentienl(限流) 和Sentinel(流控) 做详细介绍学习,欢迎评论区讨论交流。
目录
第一章 配置管理--Nacos中的配置
Nacos作为Spring Cloud Alibaba的一个重要组件,它不仅可以用作服务注册与发现,也可以用来替代Spring Cloud Config作为统一配置文件管理,而且他的使用更为简单和人性化。
1、Nacos添加配置
第一步:打开Nacos监控面板 - 进入配置列表 -点击 “+” 图标添加配置 如下:
第二步:填写Data ID,选择YAML,编辑配置文件内容
这里定义了一个名字为application-user-dev.yaml的配置,使用的是YAML格式。
-
Data ID
: 非常重要,可以看做是配置的文件的名字,在程序中拉取配置文件的时候需要指定Data ID。 -
Group
: 分组,默认是 DEFAULT_GROUP , 可以针对不同的项目指定不同的配置组。
2、客户端接入配置中心
2.1、导入依赖
添加配置中心依赖nacos-config,完整pom.xml如下。
<dependencies>
<!-- 配置中心客户端-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- 服务注册与发现-->
<dependency>
<groupId>com.alibaba.cloud </groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.example</groupId>
<artifactId>springcloudalibaba-user-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
2.2、编写Controller
@RefreshScope
注解是用来做配置自动刷新。那么当我们修改了Nacos中的配置文件,Controller中读取到的配置temp.notify
将会自动变化。
@RestController
@RefreshScope //刷新配置
public class OrderController {
@Autowired
public UserFeigoncCients userFeigoncCients;
@GetMapping("/order/{id}")
public User order(@PathVariable("id") Long id){
return userFeigoncCients.user(id);
}
}
2.3、修改yml配置
spring:
profiles:
active: dev #环境
cloud:
nacos:
config:
prefix: application-order #前缀
file-extension: yaml #后缀
server-addr: localhost:8848 #地址
extension-configs: #公共配置
- application.yaml
-
spring.cloud.nacos.config.server-addr
:配置了Nacos的地址 -
spring.cloud.nacos.config.file-extension
:指定了配置文件的格式为YAML,默认是properties, -
spring.cloud.nacos.config.prefix
:配置前缀,如果不配置前缀默认会把 服务名即spring.application.name
的值作为前缀 -
</spring.cloud.nacos.config.group
:分组名,默认是DEFAULT_GROUP对应了Nacos配置中的Group