Microservice related articles:
This article mainly has the following contents:
- Why do you need a configuration center?
- how to use
Nacos Config
Note : The code in this part is changed based on the code in [Microservice 01]
Why do you need a configuration center
When the configuration center is not used, the configuration methods of our project are generally as follows
- Write in the configuration file of the project as
application.yml
in.- Hard-coded into the code, such as using
Java
code configurationMyBatis
, etc.- Environment/Startup variable: pass in the configuration item through the environment variable of the operating system, or the -D parameter in the startup command.
- Fetch from database/cache, save configuration items in database.
The above methods have more or less their own disadvantages. When we need to modify the configuration items in the first three, we usually need to restart the application configuration items to take effect, while the fourth method seems to be unnecessary, but configuration files are used as code resources. Part of it, we cannot do version control or configuration rollback of configuration items.
Therefore, we need a configuration method that can solve the above problems, so Nacos
debut.
Introduction to Nacos
Components are used in microservice 01Nacos
, but there is no related introduction, so here is a brief introduction nacos
. The following content comes from Nacos official website :
Nacos
/nɑ:kəʊs/ is the acronym Dynamic Naming and Configuration Service
for , a dynamic service discovery, configuration management and service management platform that is easier to build cloud-native applications.
Nacos
Dedicated to helping you discover, configure, and manage microservices. Nacos
Provides a set of easy-to-use feature sets to help you quickly realize dynamic service discovery, service configuration, service metadata, and traffic management.
Nacos
帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos
是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施。
Nacos生态图:
图片来自nacos官网
如何使用Nacos Config
该部分主要涉及以下内容:
@RefreshScope
注解使用- 配置文件的配置
配置中心在项目中的使用
在 consumer-service
的 pom.xml
添加下列依赖:
<!-- 添加Nacos Config配置项 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!-- 读取bootstrap文件 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<!-- 添加这两个依赖的目的是为了演示Nacos配置中心起了作用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
<scope>runtime</scope>
</dependency>
复制代码
注意:额外添加了spring-data-jpa
和mysql-connector-java
的依赖!
接着在resources
目录下创建bootstrap.yml
文件添加并如下配置信息:
spring:
application:
name: consumer-application
cloud:
nacos:
config:
server-addr: http://192.168.1.7:8848
file-extension: yml
# prefix: 文件名前缀,默认是spring.application.name
namespace: dev
cluster-name: Cluster-A
group: DEFAULT_GROUP
# 从Nacos读取配置项的超时时间
timeout: 5000
# 长轮询超时时间
config-long-poll-timeout: 10000
# 轮询的重试时间
config-retry-time: 2000
# 长轮询最大重试次数
max-retry: 3
# 开启监听和自动刷新
refresh-enabled: true
复制代码
配置项说明
文件定位配置项:告诉应用从那个Nacos
服务器的哪一个分组中去读取配置文件
namespace
:Nacos Config
的namespace
和Nacos
作为服务发现阶段配置中namespace
是同一个概念和用法。在这里指定了namespace=dev
,应用程序则只会去获取dev
这个命名空间下的配置文件;group
:概念和用法与Nacos
服务发现中的group
相同,如未指定则默认值为DEFAULT_GROUP
,应用程序只会加载相同与配置文件中group
值相同的配置文件;prefix
:需要加载的文件名前缀,默认为当前应用的名称,即spring.application.name
,一般不需要特殊配置;file-extension
:需要加载的文件扩展名,默认为properties
,我改成了yml
超时和重试配置项:读取失败的超时和重试策略
timeout
:从Nacos
服务器上读取配置项的超时时间,单位是 ms,默认值 3000 毫秒;config-retry-time
:获取配置项失败的重试时间;config-long-poll-timeout
:长轮询超时时间,单位为 ms;max-retry
:最大重试次数。
注意:必须把name
属性从application.yml
迁移过来,否则无法动态刷新
然后再在Nacos
控制台添加consumer-appliaiton.yml;
配置文件,配置信息如下所示:
refreshData: true
spring:
datasource:
url: jdbc:mysql://localhost:3306/react?serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
#jpa
jpa:
show-sql: true
hibernate:
ddl-auto: update
复制代码
我的配置如下图所示:
consumer-application.yml创建和配置
Data ID
和 GROUP
需要和 bootstrap.yml
中的配置项保持一致。
为了验证 nacos
中新建的配置文件起了作用,在 consumer-service
添加实体类 Student
@Table
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "stu_id", nullable = false)
private Integer stuId;
@Column(name = "stu_name")
private String stuName;
@Column(name = "stu_age")
private Integer stuAge;
@Column(name = "stu_address")
private String stuAddress;
// getter and setter 省略
}
复制代码
接下来先后启动 produce-service
和 consumer-service
可在控制台看到如下信息:
建表语句截图
订阅通知截图
第一张截图表示建表成功,第二张表示我们配置文件的订阅通知。
除此之外,应用的成功启动表明了 bootstrap.yml
的加载顺序在 application.yml
之前,配置中心的配置信息读取先于 application.yml
。
先通过 bootstrap.yml
定位从那个服务器上读取配置信息,定位服务器后读取相应的配置文件供应用使用。在这里就是读取 bootstrap.yml
的配置去定位配置中心服务器,从配置中心的 consumer-application.yml
加载数据库配置信息供服务建表时使用。
注:如果要添加其他的配置文件,如消息队列、redis
等中间件的配置。 需要在spring.nacos.config
节点下添加下列配置信息
extension-configs:
- dataId: redis-config.yml
group: EXT_GROUP # 动态刷新
refresh: true
- dataId: rabbitmq-config.yml
group: EXT_GROUP
refresh: true
复制代码
注意看dataId
和group
的取值
redis和RocketMQ配置截图
配置信息的动态刷新
在ConsumerController
类上添加@RefreshScope
注解 通过@value
注入值,修改后的代码如下
@RestController
@RequestMapping("consumer/")
@RefreshScope
public class ConsumerController {
@Resource
ProduceDataInt produceDataInt;
@Value("${refreshData:true}")
private Boolean refreshData;
@GetMapping("string")
public String consumer(){
System.out.println("refreshData = " + refreshData);
System.out.println(produceDataInt.getData().get("produce"));
return "consumer user";
}
}
复制代码
Access consumer/string
the method first to get the following output:
print true for the first time
Then modify the configuration file refreshData: false
, visit the method again, and refreshData
the value you can see has changed
Access print false after modification
The above is a simple usage Nacos
as a configuration center.