前面我们已经学习过 Spring Cloud Config 了:

它提供了配置中心的功能,但是需要配合 git、svn 或外部存储(例如各种数据库),且需要配合 Spring Cloud Bus 《Spring Cloud 系列之 Bus 消息总线》实现配置刷新。

前面的课程中我们也学习了 Spring Cloud Consul,当时讲解了它作为注册中心的使用方案,且作为 Spring Cloud 官方推荐替换 Eureka 注册中心的方案。既然使用了 Consul,就可以使用 Consul 提供的配置中心功能,并且不需要额外的 git 、svn、数据库等配合,且无需配合 Bus 即可实现配置刷新。

Spring Cloud 官方声明 Consul 可以作为 Spring Cloud Config 配置中心的替代方案。

官方文档:https://cloud.spring.io/spring-cloud-static/spring-cloud-consul/2.2.2.RELEASE/reference/html/#spring-cloud-consul-config

关于 Consul 注册中心部分我们已经学习过,未学习的同学请参考之前的课程进行学习。今天我们主要讲解 Consul 作为配置中心如何使用。

Consul 介绍

Consul 是 HashiCorp 公司推出的开源工具,用于实现分布式系统的服务发现与配置。与其它分布式服务注册与发现的方案,Consul 的方案更“一站式”,内置了服务注册与发现框架、分布式一致性协议实现、健康检查、Key/Value 存储(配置中心)、多数据中心方案,不再需要依赖其它工具(比如 ZooKeeper 等),使用起来也较为简单。

Consul 使用 Go 语言编写,因此具有天然可移植性(支持Linux、Windows 和 Mac OS);安装包仅包含一个可执行文件,方便部署,与 Docker 等轻量级容器可无缝配合。

Consul 特性

  • Raft 算法

  • 服务发现

  • 健康检查

  • Key/Value 存储(配置中心)

  • 多数据中心

  • 支持 http 和 dns 协议接口

  • 官方提供 Web 管理界面

Consul 安装

点击链接观看:Consul 安装视频(获取更多请关注公众号「哈喽沃德先生」)

Consul 是用 go 语言编写的第三方工具需要单独安装使用。

下载

访问 Consul 官网:https://www.consul.io 下载 Consul 的最新版本。

支持多种环境安装,截图中只显示了部分环境。

安装

单节点和集群的安装方式在之前的课程中已经详细讲解过,这里主要讲解 Consul 配置中心的作用,我们在 Windows 安装一个单节点的 Consul 即可。

下载后的压缩包中就只有一个 consul.exe 的执行文件。

cd 到对应的目录下,使用 cmd 启动 Consul

# -dev表示开发模式运行
consul agent -dev -client=0.0.0.0

为了方便启动,也可以在 consul.exe 同级目录下创建一个脚本来启动,脚本内容如下:

consul agent -dev -client=0.0.0.0
pause

访问管理后台:http://localhost:8500/ 看到下图意味着我们的 Consul 服务启动成功了。

初始化配置

点击链接观看:初始化配置信息视频(获取更多请关注公众号「哈喽沃德先生」)

创建基本目录

使用 Consul 作为配置中心,第一步我们先创建目录,把配置信息存储至 Consul。

点击菜单 Key/Value 再点击 Create 按钮。

创建 config/ 基本目录,可以理解为配置文件所在的最外层文件夹。

创建应用目录

点击 config 进入文件夹。

再点击 Create 按钮。

创建 orderService/ 应用目录,存储对应微服务应用的 default 环境配置信息。

多环境应用目录

假设我们的项目有多环境:defaulttestdevprod,在 config 目录下创建多环境目录。

  • orderService 文件夹对应 default 环境
  • orderService-test 文件夹对应 test 环境
  • orderService-dev 文件夹对应 dev 环境
  • orderService-prod 文件夹对应 prod 环境

初始化配置

dev 环境为例,点击 orderService-dev 进入文件夹。

点击 Create 按钮准备创建 Key/Value 配置信息。

填写 Key:orderServiceConfig

填写 Value:

name: order-service-dev
mysql:
host: localhost
port: 3006
username: root
password: root

假设以上内容为订单微服务的配置信息,下面我们通过案例来加载 Consul 配置中心中的配置信息。

环境准备

consul-config-demo 聚合工程。SpringBoot 2.2.4.RELEASESpring Cloud Hoxton.SR1

  • order-service:订单服务
  • order-service02:订单服务

实践案例

点击链接观看:Consul 配置中心实践视频(获取更多请关注公众号「哈喽沃德先生」)

添加依赖

需要从 Consul 获取配置信息的项目主要添加 spring-cloud-starter-consul-config 依赖,完整依赖如下:

order-serviceorder-service02 依赖一致。

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId>
<artifactId>order-service</artifactId>
<version>1.0-SNAPSHOT</version> <!-- 继承父依赖 -->
<parent>
<groupId>com.example</groupId>
<artifactId>consul-config-demo</artifactId>
<version>1.0-SNAPSHOT</version>
</parent> <!-- 项目依赖 -->
<dependencies>
<!-- spring boot web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring boot actuator 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- spring cloud consul discovery 服务发现依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!-- spring cloud consul config 配置中心依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency> <!-- spring boot test 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> </project>

配置文件

老规矩,配置文件必须叫 bootstrap.yml 我们除了使用 Consul 配置中心功能之外,把微服务也注册到 Consul 注册中心去。order-serviceorder-service02 的配置项中除了端口和注册实例 id 之外,其余配置项一致,完整配置如下:

server:
port: 9090 # 端口 spring:
application:
name: order-service # 应用名称
profiles:
active: dev # 指定环境,默认加载 default 环境
cloud:
consul:
# Consul 服务器地址
host: localhost
port: 8500
# 配置中心相关配置
config:
# 是否启用配置中心,默认值 true 开启
enabled: true
# 设置配置的基本文件夹,默认值 config 可以理解为配置文件所在的最外层文件夹
prefix: config
# 设置应用的文件夹名称,默认值 application 一般建议设置为微服务应用名称
default-context: orderService
# 配置环境分隔符,默认值 "," 和 default-context 配置项搭配
# 例如应用 orderService 分别有环境 default、dev、test、prod
# 只需在 config 文件夹下创建 orderService、orderService-dev、orderService-test、orderService-prod 文件夹即可
profile-separator: '-'
# 指定配置格式为 yaml
format: YAML
# Consul 的 Key/Values 中的 Key,Value 对应整个配置文件
data-key: orderServiceConfig
# 以上配置可以理解为:加载 config/orderService/ 文件夹下 Key 为 orderServiceConfig 的 Value 对应的配置信息
watch:
# 是否开启自动刷新,默认值 true 开启
enabled: true
# 刷新频率,单位:毫秒,默认值 1000
delay: 1000
# 服务发现相关配置
discovery:
register: true # 是否需要注册
instance-id: ${spring.application.name}-01 # 注册实例 id(必须唯一)
service-name: ${spring.application.name} # 服务名称
port: ${server.port} # 服务端口
prefer-ip-address: true # 是否使用 ip 地址注册
ip-address: ${spring.cloud.client.ip-address} # 服务请求 ip

配置文件实体类

order-serviceorder-service02 实体类代码一致。

package com.example.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Component
@ConfigurationProperties(prefix = "mysql")
public class MySQLProperties { private String host;
private Integer port;
private String username;
private String password; public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public Integer getPort() {
return port;
} public void setPort(Integer port) {
this.port = port;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} }

控制层

order-serviceorder-service02 控制层代码一致。

注意需要添加 @RefreshScope 注解用于重新刷新作用域实现属性值自动刷新。

package com.example.controller;

import com.example.config.MySQLProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; @RefreshScope
@RestController
public class ConfigController { @Autowired
private MySQLProperties mySQLProperties; @Value("${name}")
private String name; @GetMapping("/name")
public String getName() {
return name;
} @GetMapping("/mysql")
public MySQLProperties getMySQLProperties() {
return mySQLProperties;
} }

启动类

order-serviceorder-service02 启动类代码一致。

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication
public class OrderServiceApplication { public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
} }

测试

修改配置信息前

访问:http://localhost:9090/name 结果如下:

访问:http://localhost:9090/mysql 结果如下:

修改配置信息

修改 Consul 配置中心 orderService-dev 环境的配置信息为:

name: order-service-dev-2.0
mysql:
host: localhost
port: 3006
username: root123
password: root123

修改配置信息后

控制台打印信息如下:

[TaskScheduler-1] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-config/order-service-dev/'}, BootstrapPropertySource {name='bootstrapProperties-config/order-service/'}, BootstrapPropertySource {name='bootstrapProperties-config/orderService-dev/'}, BootstrapPropertySource {name='bootstrapProperties-config/orderService/'}]
[TaskScheduler-1] o.s.boot.SpringApplication : The following profiles are active: dev
[TaskScheduler-1] o.s.boot.SpringApplication : Started application in 3.748 seconds (JVM running for 142.28)
[TaskScheduler-1] o.s.c.e.event.RefreshEventListener : Refresh keys changed: [name, mysql.password, mysql.username]

Consul 使用 Spring 定时任务 Spring TaskScheduler来监听配置文件的更新。

默认情况下,它是一个定时任务线程池 ThreadPoolTaskScheduler,其poolSize值为 1。要更改TaskScheduler,请创建一个 TaskScheduler 使用 ConsulConfigAutoConfiguration.CONFIG_WATCH_TASK_SCHEDULER_NAME 常量命名的 bean 类型。

访问:http://localhost:9090/name 结果如下:

访问:http://localhost:9090/mysql 结果如下:

总结

HashiCorp 公司的 Consul 可谓是一款全能组件。可用于提供服务发现和服务配置的工具。用 go 语言开发,具有很好的可移植性,被 Spring Cloud 纳入其中。

在注册中心方面,Netflix Eureka 停止新版本开发,Consul 成为了优秀的可替代方案。

在配置中心方面,Consul 亦可替代 Spring Cloud Config 作为配置中心使用,且无需配合 Git、SVN 等工具,无需配合 Bus 消息总线即可实现集群配置更新。

本文采用 知识共享「署名-非商业性使用-禁止演绎 4.0 国际」许可协议

大家可以通过 分类 查看更多关于 Spring Cloud 的文章。

Spring Cloud 系列之 Consul 配置中心的更多相关文章

  1. Spring Cloud 系列之 Consul 注册中心(二)

    本篇文章为系列文章,未读第一集的同学请猛戳这里:Spring Cloud 系列之 Consul 注册中心(一) 本篇文章讲解 Consul 集群环境的搭建. Consul 集群 上图是一个简单的 Co ...

  2. Spring Cloud 系列之 Config 配置中心(二)

    本篇文章为系列文章,未读第一集的同学请猛戳这里:Spring Cloud 系列之 Config 配置中心(一) 本篇文章讲解 Config 如何实现配置中心自动刷新. 配置中心自动刷新 点击链接观看: ...

  3. Spring Cloud 系列之 Config 配置中心(三)

    本篇文章为系列文章,未读前几集的同学请猛戳这里: Spring Cloud 系列之 Config 配置中心(一) Spring Cloud 系列之 Config 配置中心(二) 本篇文章讲解 Conf ...

  4. Spring Cloud 系列之 Apollo 配置中心(二)

    本篇文章为系列文章,未读第一集的同学请猛戳这里:Spring Cloud 系列之 Apollo 配置中心(一) 本篇文章讲解 Apollo 部门管理.用户管理.配置管理.集群管理. 点击链接观看:Ap ...

  5. Spring Cloud 系列之 Apollo 配置中心(三)

    本篇文章为系列文章,未读前几集的同学请猛戳这里: Spring Cloud 系列之 Apollo 配置中心(一) Spring Cloud 系列之 Apollo 配置中心(二) 本篇文章讲解 Apol ...

  6. Spring Cloud 系列之 Apollo 配置中心(四)

    本篇文章为系列文章,未读前几集的同学请猛戳这里: Spring Cloud 系列之 Apollo 配置中心(一) Spring Cloud 系列之 Apollo 配置中心(二) Spring Clou ...

  7. Spring Cloud 系列之 Config 配置中心(一)

    服务配置现状 配置文件是我们再熟悉不过的,在微服务系统中,每个微服务不仅仅只有代码,还需要连接其他资源,例如数据库的配置或功能性的开关 MySQL.Redis .Security 等相关的配置.除了项 ...

  8. Spring Cloud 系列之 Consul 注册中心(一)

    Netflix Eureka 2.X https://github.com/Netflix/eureka/wiki 官方宣告停止开发,但其实对国内的用户影响甚小,一方面国内大都使用的是 Eureka ...

  9. Spring Cloud 系列之 Apollo 配置中心(一)

    背景 随着程序功能的日益复杂,程序的配置日益增多:各种功能的开关.参数的配置.服务器的地址等等. 对程序配置的期望值也越来越高:配置修改后实时生效,灰度发布,分环境.分集群管理配置,完善的权限.审核机 ...

随机推荐

  1. django基础(一) - 安装和配置文件

    django介绍 Django是一个开放源代码的Web应用框架,由Python写成.采用了MVC的软件设计模式,即模型M,视图V和控制器C. <div style='color: red'> ...

  2. react: typescript interface useState issue

    define interface: interface ILoginState { imageId: string; imageSrc: string; username: string; passw ...

  3. 开发一款图片压缩工具(二):使用 pngquant 实现图片压缩

    上一篇我尝试使用了 pillow 库对 png 图片进行了压缩,效果不好.这次我换用 pngquant 来压缩.pngquant 是用于 PNG 图像有损压缩的命令行实用程序和库.压缩程序会显著减小文 ...

  4. VUE前端项目配置代理解决跨域问题

    VUE前端项目配置代理解决跨域问题 问题如下,经常在本地调试接口出现这种问题 解决方式1:Chrome 的扩展插件 以前使用Chrome 的扩展插件,但是有时候还是会出现莫名其妙的问题. 需要梯子才行 ...

  5. 安卓微信浏览器中window.location.href失效的问题

    最近接手一微信项目,测试功能时,发现跳转在android手机上不动了.iso系统可以正常跳转的.解决方法: window.location.href = url + '?v=' + (new Date ...

  6. curl请求curl_exec返回false,curl_error返回空

    网上查找了一下,由于采用https协议,一定要加入以下两句 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同 curl_setopt ...

  7. python学习08排序算法举例

    '''''''''排序算法:前提是所有数按照从小到大的顺序排列.1.冒泡算法将第一数与第二个数比较大小,如果第一个数比第二个数大,则沉底(交换位置,使大数在小数后面,这个过程类似于大泡沉底的过程) ' ...

  8. java中的Atomic类

    文章目录 问题背景 Lock 使用Atomic java中的Atomic类 问题背景 在多线程环境中,我们最常遇到的问题就是变量的值进行同步.因为变量需要在多线程中进行共享,所以我们必须需要采用一定的 ...

  9. SpringBoot @ConfigurationProperties详解

    文章目录 简介 添加依赖关系 一个简单的例子 属性嵌套 @ConfigurationProperties和@Bean 属性验证 属性转换 自定义Converter SpringBoot @Config ...

  10. 《Arduino实战》——3.4 小结

    本节书摘来异步社区<Arduino实战>一书中的第3章,第3.4节,作者:[美]Martin Evans ,Joshua Noble ,Jordan Hochenbaum,更多章节内容可以 ...