consul教程:springboot使用consul作为配置中心

介绍

本工程根据下面工程进行升级改造:
consul教程:springboot服务注册与发现(2)-服务提供者notice

工程下载

本工程:
https://gitee.com/65242847/springcloud_consul/tree/master/notice_consul_config

所有工程:
https://gitee.com/65242847/springcloud_consul

搭建说明

启动微服务时,首先从 consul 获取配置,然后再启动微服务,连接mysql数据库等

工程结构图

工程结构与 consul教程:springboot服务注册与发现(2)-服务提供者notice 相同

只有两处不同:

  • 多了 bootstrap.yml 配置文件
  • application.yml 配置文件是空的,可以没有

bootstrap.yml

  • 配置了consul作为服务注册的信息,如:ip、port
  • 配置了consul作为配置中心的信息
    其中 prefixformatdata-key 是关键项,表示consul中的 key 是:config/notice-service,dev/data
  1. spring:
  2. cloud:
  3. consul:
  4. host: localhost
  5. port: 8500
  6. discovery:
  7. serice-name: ${spring.application.name}
  8. deregister: true # 服务停止时取消注册
  9. # 健康检查的接口,默认为 /actuator/health,由 Spring Boot Actuator 提供
  10. health-check-path: /actuator/health
  11. config:
  12. enabled: true # 启用consul配置
  13. prefix: config # 文件夹
  14. format: YAML # 文件格式 YAML、FILES、PROPERTIES、默认 KEY-VALUE
  15. data-key: data # 默认为data
  16. application:
  17. name: notice-service # 指定服务名字,在eureka管理页面中可查看
  18. profiles:
  19. active: dev

consul添加配置(关键)

consul中的配置是以 key/value 存储的,类似 java 中的 Map根据 key 找到 value

访问服务

启动 consul 服务后,访问: http://localhost:8500/ui/

如下图,点击链接:

然后点击 【create】 按钮,如下图:

显示如下图,需要填写key和value

key(关键)

key的命名,与本工程中 bootstrap.yml 配置相关,必须一致,否则不好使

  1. config/notice-service,dev/data

key 与 bootstrap.yml 的关系

如下图:

value(关键)

consul教程:springboot服务注册与发现(2)-服务提供者notice 工程中 application.yml 中的所有内容,如下:

  1. spring:
  2. datasource:
  3. type: com.alibaba.druid.pool.DruidDataSource
  4. driver-class-name: com.mysql.jdbc.Driver
  5. url: jdbc:mysql://localhost:3308/test?characterEncoding=utf8 #不能使用域名
  6. username: root
  7. password:
  8. druid:
  9. # 连接池的配置信息
  10. # 初始化大小,最小,最大
  11. initial-size: 5
  12. min-idle: 5
  13. maxActive: 20
  14. # 配置获取连接等待超时的时间
  15. maxWait: 60000
  16. # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
  17. timeBetweenEvictionRunsMillis: 60000
  18. # 配置一个连接在池中最小生存的时间,单位是毫秒
  19. minEvictableIdleTimeMillis: 300000
  20. validationQuery: SELECT 1
  21. testWhileIdle: true
  22. testOnBorrow: false
  23. testOnReturn: false
  24. # 打开PSCache,并且指定每个连接上PSCache的大小
  25. poolPreparedStatements: true
  26. maxPoolPreparedStatementPerConnectionSize: 20
  27. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
  28. filters: stat,wall,slf4j
  29. # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
  30. connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
  31. # 整合mybatis
  32. mybatis:
  33. config-location: classpath:mybatis/mybatis-config.xml #mybatis总配置文件
  34. mapperLocations: classpath:mybatis/mapper/*.xml # xxxMapper.xml配置文件
  35. server:
  36. port: 8082

原文出处:https://malaoshi.top/show_1IXSURp2hNH.html