consul配置中心的实现与解决的问题

446 阅读1分钟

consul配置中心解决的问题

1、在我们环境发生变化时,我们通常需要更改配置文件重新配置路径和端口号,多个微服务配置同样的配置显得非常繁琐,所以我们在consul服务器中配置一次即可处处使用

consul配置中心实现

1、首先添加依赖坐标consul配置

<!--spring cloud consul config-->  
<dependency>  
    <groupId>org.springframework.cloud</groupId>  
    <artifactId>spring-cloud-starter-consul-config</artifactId>  
</dependency>  
<dependency>  
    <groupId>org.springframework.cloud</groupId>  
    <artifactId>spring-cloud-starter-bootstrap</artifactId>  
</dependency>

2、在resources目录下添加bootstrap.yml配置文件(用于配置consul)

spring:  
 application:  
  name: cloud-payment-service  
  
 cloud:  
  consul:  
   host: localhost  
   port: 8500  
 discovery:  
  service-name: ${spring.application.name}  
 config:  
  profile-separator: '-' # 覆盖默认,分割文件名 使用-  
  format: yaml  
  
# watch:  
# wait-time: 1 //动态更新配置响应时间 尽量别改

3、在consul客户端的key-value中添加配置文件夹(文件夹名以config开头以/结尾)

image.png

image.png 创建子目录(以微服务模块命名加环境(dev、prod、default))

image.png 创建data文件,编写配置

image.png 4、在模块启动类中添加@RefreshScope注解,consul配置更新55后本地文件即可生效

image.png 5、更改application.yml文件

image.png

consul配置持久化

1、在consul.exe同级目录下创建mydata和consul_start.bat(mydata用于存储配置,consul_start.bat用于启动consul)

image.png

2、编写consul_start.bat(路径改为自己的路径)

@echo.服务启动........
@echo off
@sc create Consul binpath="D:\consul\consul_1.17.1_windows_386\consul.exe agent -server -ui -bind=127.0.0.1 -client=0.0.0.0 -bootstrap-expect 1 -data-dir D:\consul\consul_1.17.1_windows_386\mydata "
@net start Consul
@sc config Consul start=AUTO
@echo.Consul start is OK........success
@pause

3、以管理员身份运行bat文件

image.png