前言
主要是为网关做一个可以动态增加,删除白名单的功能,以达到可以直接修改 URL 就可以做过滤,而不必修改本机白名单文件再重启项目。由于1.x 和 2.x 关于刷新那块不一致,说明下环境:
- Spring Boot 2.0.3.RELEASE
- Spring Cloud Finchley. RELEASE
- Spring Cloud Config
- Spring Cloud Bus
- RabbitMQ
Config Server配置
除了配置一个简单的Config Server,还要额外加入bus 和 actuator 依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
部分相关配置
spring:
cloud:
config:
server:
git:
uri:
search-paths: config-repo
username:
password:
bus:
trace:
enabled: true # 跟踪总线事件
rabbitmq:
host: 127.0.0.1
port: 5672
username: test
password: 123456
endpoints:
default:
web:
enabled: true
management:
endpoints:
web:
exposure:
include: "*"
网关端配置
网关这里作为Config-Server的一个Client连接,不过还是通过注册中心连接。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
部分相关配置
spring:
cloud:
config:
profile: dev
label: master
fail-fast: true
name: gateway-config
discovery:
enabled: true
# config-server's application name
service-id: config-server
rabbitmq:
host: 127.0.0.1
port: 5672
username: test
password: 123456
zuul:
#ignored-services: consul
retryable: true
endpoints:
default:
web:
enabled: true
management:
endpoints:
web:
exposure:
include: bus-refresh
@Component
@RefreshScope
public class WhiteListPool {
@Value("${white.list}")
public Set<String> value;
public Set<String> getValue() {
System.out.println(value.toString());
return value;
}
}
@Slf4j
public class SimpleFilter extends ZuulFilter {
@Autowired
private WhiteListPool pool;
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
...
}
public boolean isWhiteList(String url){
return pool.getValue().stream().anyMatch(url::contains);
}
}
active
- 改变配置仓库中的配置文件
- 触发config-server的刷新通知
http://localhost:5555/actuator/bus-refresh
2.0之前http://localhost:5555/bus/refresh - 跟踪总线事件
http://localhost:5555/actuator/httptrace
2.0之前http://localhost:5555/trace - 访问网关已会验证最新白名单