美文网首页
spring cloud config

spring cloud config

作者: 持而盈 | 来源:发表于2017-12-04 19:09 被阅读11次

    搭建Config Server

    新建一个Spring Boot应用

    引入maven依赖

    注意spring-cloud-config-server的版本在1.40以上才支持JDBC配置

        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-config-server</artifactId>
                <version>1.4.0.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
    
        </dependencies>
    

    配置application.yml

    spring:
      application:
        name: CONFIG-SERVER
        
      # 配置一个数据源
      datasource:
        url: jdbc:mysql://ubuntu:3306/spring?characterEncoding=utf-8&useSSL=true
        username: root
        password: root
    
    
      profiles:
        # 此处必须指定配置仓库的类型, 可以选git snv等, 也可以写多个. 这里用的是数据库.
        active: jdbc
      cloud:
        config:
          server:
            jdbc:
              # 重写查询Sql, 原SQL中KEY是关键字需要加反引号
              sql: 'SELECT `KEY`, VALUE from PROPERTIES where APPLICATION=? and PROFILE=? and LABEL=?'
    
    management:
      security:
        enabled: false
    

    数据库中创建配置表

    表名和列名都是固定的.

    
    CREATE TABLE PROPERTIES
    (
      APPLICATION VARCHAR(255) NULL,
      PROFILE     VARCHAR(255) NULL,
      LABEL       VARCHAR(255) NULL,
      `KEY`       VARCHAR(255) NULL,
      VALUE       VARCHAR(255) NULL
    );
    

    注意这里有个大坑, 我跟源码才找到, LABEL的值必须是master(不能为空),源码中把NULL值转成master。

    客户端搭建

    maven依赖

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-config</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
    

    顺便把监控的包也引入了。

    配置bootstrap.yml

    server:
      port: 8002
    
    spring:
      application:
        name: ORDER-SERVICE
      cloud:
        config:
          uri: http://localhost:8080
          # 指定要用哪个配置文件
          profile: sit
    
    management:
      security:
        enabled: false
    

    注意:上面的配置必须写在bootstrap中,否则不生效。

    在应用中引入配置属性

    @ConfigurationProperties(prefix = "order")
    @Data
    public class ConfigDemo {
        private String name;
        private String price;
    }
    
    

    综合使用config-server和config-client

    数据库的配置

    image.png

    客户端服务/env

    image.png

    相关文章

      网友评论

          本文标题:spring cloud config

          本文链接:https://www.haomeiwen.com/subject/apcwbxtx.html