由于搭建动态网关是在上个例子基础上搭建的,配置完毕后,死活不成功。而且配置肯定没错,但就是不生效。找了几天原因,终于找到了。
配置中心的客户端的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上的文件里面去,再次刷新。
就可以看到服务自动添加到网关里面去了