springcloud config 分布式配置中心
一、介紹
1、場景:
微服務系統中,系統多、實例多,如果每個系統都有自己一套配置加載、維護的機制,會導致在生產過程中因為配置問題引發的不必要的溝通成本、故障風險。需要采用分布式配置中心統一管理、統一實現方式。
2、Spring cloud config特性
服務端:存儲方式(git、svn、本地文件)、配置讀取方式(環境化、多項目倉庫)、安全性(訪問密碼、加密存儲)、自動刷新。
客戶端:加載遠程配置、刷新配置、@refreshscope作用域刷新、集成消息總線。
二、docker中運行gitlab、rabbitmq的方式
1、下載安裝: docker toolbox
windows下載:https://www.docker.com/products/docker-toolbox
下載后控制臺執行命令:docker-machine create –engine-registry-mirror=”https://s0iielsh.mirror.aliyuncs.com” –engine-insecure-registry=”0.0.0.0/0” -d virtualbox default
這時可能提示沒有boot2docker鏡像,這樣默認就會通過git下載,但是速度實在受不了,根本跑不動,但是可以直接通過安裝的docker文件夾中找到
直接復制到C:\Users\Administrator.docker\machine\cache
2、 查看虛擬機IP等信息:docker-machine env default
注:如果想直接在windows命令窗口內使用docker命令,將上一條命令輸出的內容,復制粘貼到控制臺執行一次即可
3、 創建docker中的網絡
docker network create dongnao_net
4、 運行gitlab
docker run -d –net=dongnao_net –publish 1443:443 –publish 18080:80 –name gitlab –restart always gitlab/gitlab-ce:latest
端口18080,通過你的虛擬機IP取訪問就可以看到頁面了
5、 運行rabbitmq
docker run -d –net=dongnao_net –name rabbitmq –publish 5671:5671 –publish 5672:5672 –publish 4369:4369 –publish 25672:25672 –publish 15671:15671 –publish 15672:15672 rabbitmq:management
連接的端口是 5672
web控制臺是 15672
6、說明
Oracle VM VirtualBox是一個管理虛擬機的工具
Docker Quickstart Terminal是用于連接操作虛擬機的
由于虛擬機經常啟動失敗,我遇到失敗的原因經常是vboxdrv服務沒有安裝或沒有成功啟動;
解決辦法:開始后第一件事就嘗試打開虛擬機,如果不成功就找到安裝目錄下的vboxdrv文件夾,
如C:\Program Files\Oracle\VirtualBox\drivers\vboxdrv,右擊VBoxDrv.inf,選安裝,然后重啟電腦。
再在virturalBox里啟動虛擬機,然后打開docker,運行命令 docker start rabbitmq來啟動rabbitmq,服務器啟動就正常了,這時也可以在瀏覽器上訪問rabbitmq和gitlab了。
三、注冊中心eureka
說明:以下代碼注釋說明得非常清楚,就不多做解釋,有疑問的歡迎留言提問!
1、pom文件
2、application.yml:
# 上下文初始化加載 info:name: Eureka servercontact: 動腦科技VIPspring:profiles:active: dev --- spring:profiles: dev server:port: 8761 eureka:client:# 是否注冊到eurekaserverregisterWithEureka: true# 是否拉取信息fetchRegistry: false# eureka server地址serviceUrl:defaultZone: http://127.0.0.1:8761/eureka/server:waitTimeInMsWhenSyncEmpty: 0# false 關閉自我保護,不管如何都要剔除心跳檢測異常的服務enableSelfPreservation: trueinstance:hostname: eureka13、bootstrap.yml
# 比application context先加載 # 應用名稱 spring:application:name: eureka-server4、啟動類
package com.dongnaoedu.springcloud;import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@SpringBootApplication @EnableEurekaServer public class EurekaApp {public static void main(String[] args) {new SpringApplicationBuilder(EurekaApp.class).web(true).run(args);} }四、server
1、application.yml:
info:name: 配置中心contact: 動腦VIPserver:port: 8888 # 使得/refresh不需要驗權 management:security:enabled: false # 訪問時需要提供用戶和密碼 security:# 這個接口不做用戶名密碼校驗, /monitor接收git刷新通知ignored: /monitoruser:name: userpassword: 12345678 encrypt:# 加解密用的秘鑰key: 12345678# rabbitmq的地址 用戶名 密碼 spring:rabbitmq:host: 192.168.99.100username: guestpassword: guestprofiles:active: dev# 不同環境的配置 --- spring:profiles: dev eureka:client:registerWithEureka: truefetchRegistry: trueserviceUrl:defaultZone: http://127.0.0.1:8761/eureka/instance:preferIpAddress: true --- spring:profiles: prod eureka:client:registerWithEureka: truefetchRegistry: trueserviceUrl:defaultZone: http://eureka1:8761/eureka/,http://eureka2:8762/eureka/,http://eureka3:8763/eureka/instance:preferIpAddress: true2、bootstrap.yml:
spring:application:# 配置文件就是用這個來做文件名的,要對應的哦。name: lession-2-config-serverprofiles:active: dev,gitcloud:config:server:# 本地文件native:# 用本地文件夾存儲配置,僅作配置示例,沒起作用。要想起作用,將上面的 active中git 改為 nativesearchLocations: file:D:\\cloud\\dongnao\\configrepo# git倉庫 gitlab地址git:# 記得在先gitlab上創建一個對應的projecturi: http://192.168.99.100:18080/root/project1.gitsearch-paths: /username: rootpassword: 12345678repos: # 不同環境不同的庫,這里的話,只有當應用中的spring.profiles.active=staging的時候才生效lession-2-sms-sys-staging:pattern: '*/staging'# 記得在先gitlab上創建一個對應的projecturi: http://192.168.99.100:18080/root/lession-2-config-repo-staging.git# 不同項目不同庫lession-2-sms-webmvc: pattern: # 這里是根據服務名稱匹配的spring.application.name- lession-2-sms-webmvc/**- lession-2-sms-webmvc*# 這里面的是本地git倉庫的,不知道配置本地git倉庫的也可以像上面一樣配置成遠程git地址uri: file:D:\cloud\dongnao\config-repo# 加解密encrypt:enabled: true # svn環境 # spring.profiles.active=subversion # spring.cloud.config.server.svn.uri=http:#127.0.0.1:1234/sms-sys/development/trunk # spring.cloud.config.server.svn.username=xxx # spring.cloud.config.server.svn.password=xxx3、啟動類
@SpringBootApplication @EnableConfigServer @EnableEurekaClient public class ConfigServerApplication {public static void main(String[] args) {new SpringApplicationBuilder(ConfigServerApplication.class).web(true).run(args);} }4、pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><!-- spring boot 封裝spring starter封裝、自動配置autoconfiguration--><parent><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-parent</artifactId><version>Dalston.SR1</version> <relativePath /> </parent><groupId>com.dongnaoedu.springcloud</groupId><artifactId>lession-2-config-server</artifactId><version>0.0.1-SNAPSHOT</version><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Dalston.SR1</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><!-- spring-boot-starter-web web項目,集成容器tomcat --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- spring-boot-starter-actuator 管理工具/web 查看堆棧,動態刷新配置 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-eureka</artifactId></dependency><!-- spring-boot-starter-security --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!-- cloud config組件 配置中心 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-config-server</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bus-amqp</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-config-monitor</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>五、客戶端
1、pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><!-- spring boot 封裝spring starter封裝、自動配置autoconfiguration--><parent><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-parent</artifactId><version>Dalston.SR1</version><relativePath /></parent><groupId>com.tony</groupId><artifactId>lession-2-sms-sys</artifactId><version>0.0.1-SNAPSHOT</version><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>Dalston.SR1</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><!-- spring-boot-starter-web web項目,集成容器tomcat --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- spring-boot-starter-actuator 管理工具/web 查看堆棧,動態刷新配置 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-eureka</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-config</artifactId></dependency><!-- spring bus 事件通知實現自動刷新 --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bus-amqp</artifactId></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.9.0</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>2、application.yml
# eureka是必須的spring:profiles:# 這里的意思是啟用dev環境active: dev--- spring:profiles: dev eureka:client:registerWithEureka: truefetchRegistry: trueserviceUrl:defaultZone: http://127.0.0.1:8761/eurekainstance:preferIpAddress: true--- spring:profiles: prod eureka:client:registerWithEureka: truefetchRegistry: trueserviceUrl:# 這里寫成eureka1,是因為我修改系統的hosts, 127.0.0.1 eureka1defaultZone: http://eureka1:8761/eurekainstance:preferIpAddress: true3、bootst.yml
spring:application:name: lession-2-sms-syscloud:config:discovery:# 使用eureka發現配置中心服務enabled: true# 配置中心服務名稱/IDserviceId: lession-2-config-server# 登錄用戶名和密碼username: userpassword: 12345678# 覆蓋本地配置overrideNone: falsefailFast: truename: ${spring.application.name}profile: ${spring.profiles.active}# git倉庫中,可以使用label來做不同版本的配置管理,默認是master,可以用來做版本管理。比如“2.0”label: 'master'4、啟動類
package com.dongnaoedu.springcloud.service;import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.context.annotation.ComponentScan;@SpringBootApplication @ComponentScan("com.dongnaoedu") @EnableEurekaClient public class SmsServiceApplication {public static void main(String[] args) {new SpringApplicationBuilder(SmsServiceApplication.class).web(true).run(args);} }5、controller
package com.dongnaoedu.springcloud.service;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;@RestController @RefreshScope // 此處很重要 +++ public class SmsController {@Value("${tony.configString}")private String configString;// 測試注入tony.configString配置@RequestMapping("/test")public String sendSms() {return "configString的值:" + configString;}@AutowiredEnvironment env;@RequestMapping("/get/{configName}")public String test(@PathVariable String configName) {return configName + "的值為:" + env.getProperty("tony." + configName);} }6、redis
package com.dongnaoedu.springcloud.service;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;import redis.clients.jedis.JedisPool;@Configuration @RestController @RequestMapping("/redis") public class RedisController {@AutowiredEnvironment env;@Bean@RefreshScope// 在refresh之后,這個實例會被刷新public JedisPool jedisPool() {String host = env.getProperty("redis.host");int port = env.getProperty("redis.port", Integer.class);return new JedisPool(host, port);}@Autowiredprivate JedisPool jedisPool;// 獲取一個key的值 并打印出來@RequestMapping("/get/{key}")public String sendSms(@PathVariable String key) {String value = jedisPool.getResource().get(key);return " redis中" + key + "的值為:" + value;} }當gitlab上的配置改變了,直接調用接口獲取到的值會是改變之前的值,得先調用refresh(post接口)接口刷新后再調用目標接口,這樣才能獲取到最新的值。
六、MVC
1、springmvc中的配置加載 和 環境化
profile激活不同環境,加載不同的配置
普通mvc程序通過 xml中 <beans profile="dev">...</beans> 方式可以進行配置
2、在xml配置文件中配置<context:property-placeholder location="classpath:sms.properties"/>就可以設置${}里取到的變量值就是sms.properties里配置的值。
3、spring cloud config 工作模式
配置項怎么配置? 通過配置文件進行配置并存儲在git中
誰去讀配置文件? configserver配置中心
應用系統中配置信息從哪來? 從configserver遠程獲取
3、全局刷新怎么實現的?
通過rabbitmq發送消息, 訂閱的客戶端(應用系統)收到消息后,判斷是否需要刷新
具體實現后面spring cloud stream/bus會講到
4、自動刷新是什么一個機制?
gitlab提交配置更新的時候,觸發一個事件(項目-設置-集成-webhook)
發起http請求到config-server monitor組件
http://192.168.99.1:8888/monitor 這是配置中心地址
configserver解析請求,通過spring cloud bus消息總線發送通知給各服務(和/bus/refresh一樣)
對應的webapi類:PropertyPathEndpoint#notifyByPath
5、安全機制:如何保證配置的保密性?
項目中的密碼 不應該明文存儲,應該是密文
configserver訪問控制:用戶名密碼
文件內容加密:configserver中設置spring.cloud.config.server.encrypt.enabled=true
再配置一個秘鑰:encrypt.key=12345678
配置文件中密文需要以{cipher}做為標識:如spring.rabbitmq.password= ‘{cipher}31010f99731d4bd8aa7e3ce76152b5686265e1160043aac7cf769c3c8e1bb7ef’
對應的web api:EncryptionController#encrypt 加密
EncryptionController#decrypt 解密
總結
以上是生活随笔為你收集整理的springcloud config 分布式配置中心的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python3 property属性
- 下一篇: 基于angular4+ng-bootst