Spring Cloud 基於Consul 實現配置服務

Spring Cloud體系中提供了Config組件來進行配置服務管理。而Consul除了提供服務註冊與發現功能外,同時也提供配置管理功能。本位將介紹如何結合Spring Cloud + Consul實現配置管理。java

本文中使用的工程及環境參考上篇文章《Spring Cloud 基於Consul 實現服務註冊與發現》mysql

添加配置依賴

在leon-consumer項目中添加配置依賴web

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
複製代碼

添加項目配置

新建bootstrap.yml文件,在文件中添加配置服務相關參數配置:spring

spring:
  application:
    name: leon-consumer
  cloud:
    consul:
      host: localhost
      port: 8500
      config:
        enabled: true
        format: yaml
        prefix: config
        default-context: leon-consumer
        data-key: data
複製代碼

添加配置文件及數據

新建application-dev.yml、application-test.yml配置文件,分別表明開發、測試環境配置文件,其中分別指定開發和測試環境的端口爲808一、8082sql

server:
  port: 8081
複製代碼
server:
  port: 8082
複製代碼

而後在application.yml中指定想要啓用的環境配置shell

spring:
  profiles:
    active: test
複製代碼

此時表明項目啓動使用測試環境,服務應該運行在8082端口,整個配置文件體系結構以下:數據庫

而後在web管理界面選擇key/value,點擊create,新增配置信息bootstrap

分別填入想要保存的配置信息,以key-value的形式保存瀏覽器

這裏key值須要和項目工程中的配置保持一致。mybatis

仔細對比,相信都能明白字段對應的位置。建議先按照默認的配置,可以正常訪問獲得數據後在進行自由更改。

spring:
 cloud:
 consul:
 host: localhost
 port: 8500
 config:
 enabled: true # 開啓配置管理服務
 format: yaml  # 配置的格式,有四種選擇
 prefix: config # 配置所在的應用目錄名稱
 default-context: leon-consumer # 服務名稱,也就是spring.application.name的值
 data-key: data # 默認爲data,能夠更改,須要和consul建立時保持一致
複製代碼

填入value值後點擊save保存便可。注意若是是YAML格式,那麼數據間的冒號後要有空格。

在項目中獲取配置

在leon-consumer項目中,新建ConfigController類,讀取線上配置信息

@RestController
public class ConfigController {

    @Value("${dbName}")
    private String dbName;

    @Value("${dbPassword}")
    private String dbPassword;

    @GetMapping("/getdbinfo")
    public String getDBInfo() {
        return "數據庫用戶名:" + dbName + " | 數據庫密碼: " + dbPassword;
    }
}
複製代碼

運行服務,而後訪問接口getdbinfo,查看結果。注意此時咱們運行是test環境,因此須要訪問8082端口。

自動刷新配置信息

可以獲取到配置信息後,此時更改線上配置數據:

此時咱們刷新瀏覽器,訪問getdbinfo接口是沒法刷新數據的。想要可以實時刷新配置數據,須要在類上添加註解 @RefreshScope

@RestController
@RefreshScope
public class ConfigController {

    @Value("${dbName}")
    private String dbName;

    @Value("${dbPassword}")
    private String dbPassword;

    @GetMapping("/getdbinfo")
    public String getDBInfo() {
        return "數據庫用戶名:" + dbName + " | 數據庫密碼: " + dbPassword;
    }
}
複製代碼

添加註解後,從新啓動服務,而後測試下就線上配置數據更改後就能夠自動更新了,不用在重啓服務。

複雜配置

上文中咱們配置了簡單的鍵值對信息,除此以外咱們還能夠配置複雜數據,更新配置數據:

dbName: leon
dbPassword: 666666
user:
 name: leon
 age: 18
 desc: 帥哥
複製代碼

在項目中添加引用

@RestController
@RefreshScope
public class ConfigController {

    @Value("${dbName}")
    private String dbName;

    @Value("${dbPassword}")
    private String dbPassword;

    @Value("${user.name}")
    private String name;

    @Value("${user.age}")
    private int age;

    @Value("${user.desc}")
    private String desc;

    @GetMapping("/getuserinfo")
    public String getUserInfo() {
        return name + " | " + age + " | " + desc;
    }

    @GetMapping("/getdbinfo")
    public String getDBInfo() {
        return "數據庫用戶名:" + dbName + " | 數據庫密碼: " + dbPassword;
    }
}
複製代碼

從新啓動後,訪問 getuserinfo 接口,能夠看到可以正常訪問

若是以爲這種方式比較繁瑣(Java但是要面向對象的啊),能夠經過一個對象類獲取整個配置信息。 添加兩個Bean類:

public class User {
    private String name;
    private int age;
    private String desc;
    //...get/set方法
}

複製代碼
@ConfigurationProperties()
public class ConfigBean {
    private String dbName;
    private String dbPassword;
    private User user;
    //...get/set方法
}
複製代碼

注意此時已經給ConfigBean添加了註解:@ConfigurationProperties() 而後給啓動類添加註解:@EnableConfigurationProperties(ConfigBean.class)

@SpringBootApplication
@EnableFeignClients
@EnableConfigurationProperties(ConfigBean.class)
public class LeonConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(LeonConsumerApplication.class, args);
    }
}
複製代碼

而後就能夠直接調用獲取信息,在以前的Controller類中添加引用:

@Autowired
private ConfigBean configBean;

@GetMapping("/getallinfo")
public String getAllInfo() {
    StringBuilder allInfo = new StringBuilder();
    allInfo.append(configBean.getDbName() + " | ");
    allInfo.append(configBean.getDbPassword() + " | ");
    allInfo.append(configBean.getUser().getName() + " | ");
    allInfo.append(configBean.getUser().getAge() + " | ");
    allInfo.append(configBean.getUser().getDesc() + " | ");
    return allInfo.toString();
}
複製代碼

從新運行服務,而後訪問接口查看信息 http://localhost:8082/getallinfo

小問題

在配置類中添加@ConfigurationProperties註解後會出現提示信息。

此提示信息不影響項目運行。 查詢事後瞭解到是由於在註解中沒有配置(prefix=""),沒有指定 classpath 時,IDEA 提示沒有找到 classpath,在spring boot1.5以上版本@ConfigurationProperties取消location註解,咱們使用1.5.21版本因此會由此問題,能夠在IDEA中配置取消提醒,具體方式能夠參考文章:blog.csdn.net/expect521/a…

配置文件使用線上配置

除去前面說的能夠在項目代碼中引用線上配置,同時還能夠在配置文件中直接引用線上配置。 在項目中添加MySQL和Mybatis的依賴

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.2.0</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
複製代碼

爲了方便,複用以前的User類。在User類中添加id字段

privata long id;
複製代碼

在項目中添加Mapper類:

@Mapper
public interface UserMapper {
    public User getDmUserById(@Param(value = "id") String id) throws Exception;
}
複製代碼

在resource目錄下添加配置文件:

<mapper namespace="cn.leon.leonconsumer.mapper.UserMapper">

    <select id="getDmUserById" resultType="cn.leon.leonconsumer.config.User">
        select
                id as id,
                name as name,
                age as age,
                description as description
        from user
        <trim prefix="where" prefixOverrides="and | or">
            <if test="id != null">
                and id=#{id}
            </if>
        </trim>
    </select>

複製代碼

修改application-test.yml文件,添加mybatis和mysql的相關配置:

server:
 port: 8082
mybatis:
 mapper-locations: classpath:mapper/*Mapper.xml
spring:
 datasource:
 url: jdbc:mysql://localhost:3306/temp?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull
 username: ${dbName}
 password: ${dbPassword}
 driver-class-name: com.mysql.jdbc.Driver
複製代碼

修改線上配置參數,配置正確的帳號和密碼

添加獲取用戶方法

@Autowired
private UserMapper userMapper;

@RequestMapping("/getUser")
public String getUser() throws Exception {
   User user =  userMapper.getDmUserById(1);
   return user.toString();
}
複製代碼

User定義的字段desc可能會和數據庫關鍵字衝突,改爲description.xml文件上文已改

而後訪問此方法,能夠看到可以正常鏈接數據庫獲取信息:

同時咱們還能夠將整個配置信息都放到線上,這樣每一個項目都不須要在本身的項目中再單獨配置。 將application-test.dev.yml中的數據庫配置信息都刪掉

而後將數據庫配置都放到線上:

而後從新啓動服務,發現正常運行,接口能夠調用。

相關文章
相關標籤/搜索