Nacos我想在网关里面写一个路由监听,生成token,但是监听函数一直都无法触发
dynamicRouteByNacosListener 是我想监听的函数,但是这个函数一直都触发不了
package com.cad.guardian.route;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.concurrent.Executor;
@Component
@RefreshScope
public class DynamicRouteServiceImplByNacos {
private static Logger logger = LoggerFactory.getLogger(DynamicRouteServiceImplByNacos.class);
@Value("${nacos.dataId}")
private String dataId;
@Value("${nacos.group}")
private String group;
@Value("${spring.cloud.nacos.discovery.server-addr}")
private String serverAddr;
@Autowired
private DynamicRouteServiceImpl dynamicRouteService;
@Bean
public String routeServiceInit() {
logger.info("-------------------------------------------------------------------------------");
logger.info("dataId:{}",dataId);
logger.info("group:{}",group);
logger.info("serverAddr:{}",serverAddr);
dynamicRouteByNacosListener(dataId,group,serverAddr);
return "success";
}
/**
* 监听Nacos Server下发的动态路由配置
* @param dataId
* @param group
*/
public void dynamicRouteByNacosListener (String dataId, String group,String serverAddr){
try {
if (group == null || group == ""){
logger.info("路由group配置为null");
return;
}
if (dataId == null || dataId == ""){
logger.info("路由dataId配置为null");
return;
}
ConfigService configService=NacosFactory.createConfigService(serverAddr);
String content = configService.getConfig(dataId, group, 5000);
logger.info("nacos初始化监听,{}",content);
configService.addListener(dataId, group, new Listener() {
@Override
public void receiveConfigInfo(String configInfo) {
try {
List<RouteDefinition> gatewayRouteDefinitions = JSONObject.parseArray(configInfo, RouteDefinition.class);
for (RouteDefinition routeDefinition : gatewayRouteDefinitions){
logger.info("遍历:" + routeDefinition.toString());
dynamicRouteService.update(routeDefinition);
}
}catch (Exception e){
logger.error("更新配置出错:",e);
}
}
@Override
public Executor getExecutor() {
return null;
}
});
} catch (NacosException e) {
logger.error("初始化nacos监听出错:",e);
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论