1 通知SpringBoot配置文件有变化
ApplicationContext..publishEvent(new EnvironmentChangeEvent(changedKeys));
2 通知gateway刷新路由
ApplicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
以apollo配置中心为例,SpringCloud gateway实现动态路由代码如下:
package com.sa.config;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
/**
* apollo动态路由
*
* @author gongmin
* @date 2024/1/23 15:06
*/
@Component
@Slf4j
public class GatewayPropertiesRefresher implements ApplicationContextAware, ApplicationEventPublisherAware {
private ApplicationContext applicationContext;
private ApplicationEventPublisher publisher;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
/**
* 监听apollo配置,实现网关路由动态更新
*
* @param changeEvent 更新事件
*/
@ApolloConfigChangeListener(value = "application.yml", interestedKeyPrefixes = "spring.cloud.gateway.")
public void onChange(ConfigChangeEvent changeEvent) {
refreshGatewayProperties(changeEvent);
}
/**
* 刷新路由
*
* @param changeEvent 更新事件
*/
private void refreshGatewayProperties(ConfigChangeEvent changeEvent) {
log.debug("<refreshGatewayProperties> start");
this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
refreshGatewayRouteDefinition();
log.debug("<refreshGatewayProperties> end");
}
/**
* 刷新路由
*/
private void refreshGatewayRouteDefinition() {
log.debug("<refreshGatewayRouteDefinition> start");
this.publisher.publishEvent(new RefreshRoutesEvent(this));
}
}