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作为配置中心的信息
    其中 prefix、format、data-key 是关键项,表示consul中的 key 是:config/notice-service,dev/data
spring:
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        serice-name: ${spring.application.name}
        deregister: true # 服务停止时取消注册
        # 健康检查的接口,默认为 /actuator/health,由 Spring Boot Actuator 提供
        health-check-path: /actuator/health

      config:
        enabled: true  # 启用consul配置
        prefix: config # 文件夹
        format: YAML  # 文件格式 YAML、FILES、PROPERTIES、默认 KEY-VALUE
        data-key: data # 默认为data

  application:
    name: notice-service  # 指定服务名字,在eureka管理页面中可查看

  profiles:
    active: dev

consul添加配置(关键)

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

访问服务

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

如下图,点击链接:

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

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

key(关键)

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

config/notice-service,dev/data

key 与 bootstrap.yml 的关系

如下图:

value(关键)

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

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3308/test?characterEncoding=utf8  #不能使用域名
    username: root
    password:


    druid:
      # 连接池的配置信息
      # 初始化大小,最小,最大
      initial-size: 5
      min-idle: 5
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      validationQuery: SELECT 1
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,slf4j
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000


# 整合mybatis
mybatis:
  config-location: classpath:mybatis/mybatis-config.xml   #mybatis总配置文件
  mapperLocations: classpath:mybatis/mapper/*.xml   # xxxMapper.xml配置文件


server:
  port: 8082

原文出处:/show_1IXSURp2hNH.html