由於搭建動態網關是在上個例子基礎上搭建的,配置完畢後,死活不成功。而且配置肯定沒錯,但就是不生效。找了幾天原因,終於找到了。
配置中心的客戶端的yml文件應該是bootstrap.yml,而不是application.yml!!!
【1】動態網關引入pom.xml
<!-- config配置中心 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
<!-- actuator監控中心 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
【2】bootstrap.yml文件
#註冊 中心
server:
port: 80
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8000/eureka/
#網關名稱,配置動態網關時,文件名應該是:bootstrap.yml
spring:
application:
name: server-zuul
cloud:
config:
####讀取後綴
profile: dev
####讀取config-server註冊地址
discovery:
service-id: config-server
enabled: true
####開啓端點監控
management:
endpoints:
web:
exposure:
include: "*"
在git上新建server-zuul-dev.yml的文件(注意文件名的對應關係),內容爲:
zuul:
routes:
api-a:
### 以 /api-member/訪問轉發到會員服務
path: /api-member/**
serviceId: member-server
api-b:
### 以 /api-order/訪問轉發到訂單服務
path: /api-order/**
serviceId: order-server
啓動類添加:
// zuul配置能夠使用config實現實時更新
@RefreshScope
@ConfigurationProperties("zuul")
public ZuulProperties zuulProperties() {
return new ZuulProperties();
}
啓動後,刷新http://127.0.0.1/actuator/refresh。
此時還可以啓動第三個服務,然後添加到git上的文件裏面去,再次刷新。
就可以看到服務自動添加到網關裏面去了