Skip to content

Commit

Permalink
增加 spring cloud gateway 网关的示例
Browse files Browse the repository at this point in the history
  • Loading branch information
YunaiV committed Feb 26, 2020
1 parent 5b11085 commit 0626cc3
Show file tree
Hide file tree
Showing 9 changed files with 241 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ server:
port: 8888

spring:
application:
name: gateway-application

cloud:
# Spring Cloud Gateway 配置项,对应 GatewayProperties 类
gateway:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ server:
port: 8888

spring:
application:
name: gateway-application

cloud:
# Spring Cloud Gateway 配置项,对应 GatewayProperties 类
gateway:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@

import java.util.ArrayList;

/**
* 由 https://github.com/ctripcorp/apollo-use-cases/tree/master/spring-cloud-gateway 提供代码,感谢~
*/
@Component
public class GatewayPropertiesRefresher implements ApplicationContextAware, ApplicationEventPublisherAware {

Expand All @@ -44,7 +47,6 @@ public void setApplicationContext(ApplicationContext applicationContext) throws
this.applicationContext = applicationContext;
}


@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
Expand All @@ -65,8 +67,11 @@ public void onChange(ConfigChangeEvent changeEvent) {
*/
private void refreshGatewayProperties(ConfigChangeEvent changeEvent) {
logger.info("Refreshing GatewayProperties!");
// <1>
preDestroyGatewayProperties(changeEvent);
// <2>
this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
// <3>
refreshGatewayRouteDefinition();
logger.info("GatewayProperties refreshed!");
}
Expand All @@ -86,10 +91,12 @@ private void refreshGatewayProperties(ConfigChangeEvent changeEvent) {
*/
private synchronized void preDestroyGatewayProperties(ConfigChangeEvent changeEvent) {
logger.info("Pre Destroy GatewayProperties!");
// 判断 `spring.cloud.gateway.routes` 配置项,是否被全部删除。如果是,则置空 GatewayProperties 的 `routes` 属性
final boolean needClearRoutes = this.checkNeedClear(changeEvent, ID_PATTERN, this.gatewayProperties.getRoutes().size());
if (needClearRoutes) {
this.gatewayProperties.setRoutes(new ArrayList<>());
}
// 判断 `spring.cloud.gateway.default-filters` 配置项,是否被全部删除。如果是,则置空 GatewayProperties 的 `defaultFilters` 属性
final boolean needClearDefaultFilters = this.checkNeedClear(changeEvent, DEFAULT_FILTER_PATTERN, this.gatewayProperties.getDefaultFilters().size());
if (needClearDefaultFilters) {
this.gatewayProperties.setRoutes(new ArrayList<>());
Expand All @@ -113,6 +120,7 @@ private void refreshGatewayRouteDefinition() {
* @author ksewen
* @date 2019/5/23 2:18 PM
*/
// 判断是否清除的标准,是通过指定配置项被删除的数量,是否和内存中的该配置项的数量一样。如果一样,说明被清空了
private boolean checkNeedClear(ConfigChangeEvent changeEvent, String pattern, int existSize) {
return changeEvent.changedKeys().stream().filter(key -> key.matches(pattern))
.filter(key -> {
Expand Down
72 changes: 72 additions & 0 deletions labx-08/labx-08-sc-gateway-demo03-config-nacos/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
<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">
<parent>
<artifactId>labx-08</artifactId>
<groupId>cn.iocoder.springboot.labs</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>labx-08-sc-gateway-demo03-config-nacos</artifactId>

<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<spring.boot.version>2.2.4.RELEASE</spring.boot.version>
<spring.cloud.version>Hoxton.SR1</spring.cloud.version>
<spring.cloud.alibaba.version>2.2.0.RELEASE</spring.cloud.alibaba.version>
</properties>

<!--
引入 Spring Boot、Spring Cloud、Spring Cloud Alibaba 三者 BOM 文件,进行依赖版本的管理,防止不兼容。
在 https://dwz.cn/mcLIfNKt 文章中,Spring Cloud Alibaba 开发团队推荐了三者的依赖关系
-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>${spring.boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring.cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring.cloud.alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<!-- 引入 Spring Cloud Gateway 相关依赖,使用它作为网关,并实现对其的自动配置 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

<!-- 引入 Spring Cloud Alibaba Nacos Discovery 相关依赖,将 Nacos 作为注册中心,并实现对其的自动配置 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

<!-- 引入 Spring Cloud Alibaba Nacos Config 相关依赖,将 Nacos 作为配置中心,并实现对其的自动配置 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package cn.iocoder.springcloud.labx08.gatewaydemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class GatewayApplication {

public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package cn.iocoder.springcloud.labx08.gatewaydemo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.context.*;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class GatewayPropertiesRefresher implements ApplicationListener<EnvironmentChangeEvent>,
ApplicationContextAware, ApplicationEventPublisherAware, EnvironmentAware {

private static final Logger logger = LoggerFactory.getLogger(GatewayPropertiesRefresher.class);

private static final String ID_PATTERN = "spring.cloud.gateway.routes";

private static final String DEFAULT_FILTER_PATTERN = "spring.cloud.gateway.default-filters";

private ApplicationContext applicationContext;

private ApplicationEventPublisher publisher;

private Environment environment;

@Autowired
private GatewayProperties gatewayProperties;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}

@Override
public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
this.publisher = publisher;
}

@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}

@Override
public void onApplicationEvent(EnvironmentChangeEvent changeEvent) {
if (true) {
return;
}
// <0> 只处理 `spring.cloud.gateway` 配置项的变更
if (!isGatewayConfigChanged(changeEvent)) {
return;
}
// <1>
preDestroyGatewayProperties(changeEvent);
// <2> 貌似不用添加。添加了就死循环了。
// this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.getKeys()));
// <3>
// refreshGatewayRouteDefinition();
}

private boolean isGatewayConfigChanged(EnvironmentChangeEvent changeEvent) {
for (String key : changeEvent.getKeys()) {
if (key.contains(ID_PATTERN)
|| key.contains(DEFAULT_FILTER_PATTERN)) {
return true;
}
}
return false;
}

private synchronized void preDestroyGatewayProperties(EnvironmentChangeEvent changeEvent) {
logger.info("Pre Destroy GatewayProperties!");
// 判断 `spring.cloud.gateway.routes` 配置项,是否被全部删除。如果是,则置空 GatewayProperties 的 `routes` 属性
final boolean needClearRoutes = this.checkNeedClear(ID_PATTERN);
if (needClearRoutes) {
this.gatewayProperties.setRoutes(new ArrayList<>());
}
// 判断 `spring.cloud.gateway.default-filters` 配置项,是否被全部删除。如果是,则置空 GatewayProperties 的 `defaultFilters` 属性
final boolean needClearDefaultFilters = this.checkNeedClear(DEFAULT_FILTER_PATTERN);
if (needClearDefaultFilters) {
this.gatewayProperties.setRoutes(new ArrayList<>());
}
logger.info("Pre Destroy GatewayProperties finished!");
}

private void refreshGatewayRouteDefinition() {
logger.info("Refreshing Gateway RouteDefinition!");
this.publisher.publishEvent(new RefreshRoutesEvent(this));
logger.info("Gateway RouteDefinition refreshed!");
}

// 判断是否清除的标准,判断指定属性是否为空。如果是,则说明被清空了。
private boolean checkNeedClear(String pattern) {
return environment.getProperty(pattern) == null;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
server:
port: 8888

spring:

cloud:
# Spring Cloud Gateway 配置项,全部配置在 Apollo 中
# gateway:

# Nacos 作为注册中心的配置项
nacos:
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址

# Apollo 相关配置项
app:
id: ${spring.application.name} # 使用的 Apollo 的项目(应用)编号
apollo:
meta: http://127.0.0.1:8080 # Apollo Meta Server 地址
bootstrap:
enabled: true # 是否开启 Apollo 配置预加载功能。默认为 false。
eagerLoad:
enable: true # 是否开启 Apollo 支持日志级别的加载时机。默认为 false。
namespaces: application # 使用的 Apollo 的命名空间,默认为 application。
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
spring:
application:
name: gateway-application

cloud:
nacos:
# Nacos Config 配置项,对应 NacosConfigProperties 配置属性类
config:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址
namespace: # 使用的 Nacos 的命名空间,默认为 null
group: DEFAULT_GROUP # 使用的 Nacos 配置分组,默认为 DEFAULT_GROUP
name: # 使用的 Nacos 配置集的 dataId,默认为 spring.application.name
file-extension: yaml # 使用的 Nacos 配置集的 dataId 的文件拓展名,同时也是 Nacos 配置集的配置格式,默认为 properties
1 change: 1 addition & 0 deletions labx-08/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<module>labx-08-sc-gateway-demo02-registry</module>

<module>labx-08-sc-gateway-demo03-config-apollo</module>
<module>labx-08-sc-gateway-demo03-config-nacos</module>

<module>labx-08-sc-user-service</module>
</modules>
Expand Down

0 comments on commit 0626cc3

Please sign in to comment.