統一配置中心概述
如果微服務架構中沒有使用統一配置中心時,所存在的問題:
- 配置檔案分散在各個項目裡,不友善維護
- 配置内容安全與權限,實際開發中,開發人員是不知道線上環境的配置的
-
更新配置後,項目需要重新開機
在SpringCloud中我們使用config元件來作為統一配置中心:
廢話不多說,本小節我們來開發統一配置中心的server端:
先在你的項目裡加一個子產品:
項目的pom.xml檔案配置的依賴如下:
<dependencies>
<!-- 配置中心 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
</dependencies>
增加一個Main方法 ConfigMain.java:
@SpringBootApplication
@EnableConfigServer // 激活該應用為配置檔案伺服器:讀取遠端配置檔案,轉換為rest接口服務
public class ConfigMain {
public static void main(String[] args) {
new SpringApplicationBuilder(ConfigMain.class).web(true).run(args);
}
}
增加 application.yml 資源檔案:
server:
port: 8040
spring:
cloud:
config:
server:
git:
uri: https://github.com/wufewu/userservice # 配置git倉庫的位址
運作Main方法,然後去浏覽器上檢視資源檔案:
通路網址:http://localhost:8040/userservice/dev
通路網址:http://localhost:8040/userservice-dev.yml
微服務項目:
将微服務的application.yml檔案内容放到git倉庫,并添加一個新的bootstrap.yml檔案
bootstrap.yml:
# 等價于:http://localhost:8040/userservice/dev
spring:
application:
# 資源檔案的字首
name: userservice
profiles:
# 指在git倉庫配置的環境
active: dev
cloud:
config:
uri: http://localhost:8040
解釋:userservice 與 dev是指:
pom.xml依賴:
<dependency>
<!-- -->
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
OK,然後照常運作。
zuul路由
Zuul簡介
路由是微服務架構的不可或缺的一部分。例如:”/” 可能映射到你應用首頁,/api/users映射到使用者服務,/api/shop映射到購物服務。Zuul。Zuul是Netflix出品的一個基于JVM路由和服務端的負載均衡器 當一個UI應用想要代理調用一個或者多個背景服務的時候,Sping cloud建立了一個嵌入的Zuul proxy很友善的開發一個簡單的案例。這個功能對于代理前端需要通路的後端服務非常有用,避免了所有後端服務需要關心管理CORS和認證的問題.
建立一個zuul子產品
在pom.xml檔案增加依賴:
<dependencies>
<!-- 開啟zuul路由 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
</dependencies>
增加Main方法, ZuulMain.java:
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy // 開啟zuul路由
public class ZuulMain {
public static void main(String[] args) {
SpringApplication.run(ZuulMain.class, args);
}
}
增加application.yml檔案:
#界面一般是80端口
server:
port: 80
#給登入微服務設定一個名字
spring:
application:
name: zuul
eureka:
instance:
prefer-ip-address: true
hostname: localhost
client:
register-with-eureka: true
fetch-registry: true
service-url:
# 下面是你的注冊中心的網址
defaultZone: http://localhost:8761/eureka/
然後去浏覽器運作你原本的代碼,路徑要改一下:
下面是我的注冊中心