可以参考一下这个动态路由的实现。我最近也有这个疑问
@RefreshScope
@Slf4j
@Component
public class DynamicRouteConfig implements ApplicationEventPublisherAware {
/**
* nacos 配置dataId
*/
@Value("${config.dynamic.route.dataId:gateway-router}")
private String dataId;
/**
* nacos 配置group
*/
@Value("${config.dynamic.route.group:DEFAULT_GROUP}")
private String group;
/**
* nacos 配置地址
*/
@Value("${spring.cloud.nacos.config.server-addr}")
private String serverAddr;
/**
* nacos namespace 配置地址
*/
@Value("${spring.cloud.nacos.config.namespace}")
private String namespace;
@Autowired
private RouteDefinitionWriter routeDefinitionWriter;
private ApplicationEventPublisher applicationEventPublisher;
private static final List<String> ROUTE_LIST = new ArrayList<>();
@PostConstruct
public void dynamicRouteByNacosListener() {
try {
// 创建ConfigService
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
properties.put(PropertyKeyConst.NAMESPACE, namespace);
ConfigService configService = NacosFactory.createConfigService(properties);
// 程序首次启动, 并加载初始化路由配置
String initConfigInfo = configService.getConfig(dataId, group, 5000);
this.addAndPublishBatchRoute(initConfigInfo);
//添加监听路由变化
configService.addListener(dataId, group, new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
clearRoute();
try {
List<RouteDefinition> gatewayRouteDefinitions = JSONObject.parseArray(configInfo, RouteDefinition.class);
for (RouteDefinition routeDefinition : gatewayRouteDefinitions) {
addRoute(routeDefinition);
}
publish();
log.info("gateway路由配置修改成功, 配置信息: {}", JSON.toJSONString(gatewayRouteDefinitions));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Executor getExecutor() {
return null;
}
});
} catch (NacosException e) {
e.printStackTrace();
}
}
private void publish() {
this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this.routeDefinitionWriter));
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
/**
* 批量 添加及发布 路由
*
* @param configInfo 配置文件字符串, 必须为json array格式
*/
private void addAndPublishBatchRoute(String configInfo) {
try {
clearRoute();
List<RouteDefinition> gatewayRouteDefinitions = JSONObject.parseArray(configInfo, RouteDefinition.class);
for (RouteDefinition routeDefinition : gatewayRouteDefinitions) {
addRoute(routeDefinition);
}
publish();
log.info("gateway路由配置初始化结束, 配置信息: {}", JSON.toJSONString(gatewayRouteDefinitions));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 清除路由信息
*/
private void clearRoute() {
for (String id : ROUTE_LIST) {
this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
}
ROUTE_LIST.clear();
}
/**
* 添加路由
*
* @param definition
*/
private void addRoute(RouteDefinition definition) {
try {
routeDefinitionWriter.save(Mono.just(definition)).subscribe();
ROUTE_LIST.add(definition.getId());
} catch (Exception e) {
e.printStackTrace();
}
}
}