SpringCloud-Gateway路由动态配置Nacos实现

  1. 编写配置类

    java 复制代码
    @Component
    public class NacosConfig {
        public static String GROUP_ID ;
        public static String DATA_ID ;
        @Value("${nacos.gateway.route.config.group}")
        public void setGroupId(String groupId){
            GROUP_ID = groupId ;
        }
        @Value("${nacos.gateway.route.config.data-id}")
        public void setDataId(String dataId){
            DATA_ID = dataId ;
        }
    }
  2. properties添加配置

    properties 复制代码
    nacos.gateway.route.config.group=DEFAULT_GROUP
    nacos.gateway.route.config.data-id=hello-gateway-router.json
  3. 自定义RouteDefinitionLocator

    java 复制代码
    @Slf4j
    @Component
    public class NcosRouteDefinitionLocator implements RouteDefinitionLocator, InitializingBean {
        private volatile List<RouteDefinition> routeDefinitions = new CopyOnWriteArrayList<>() ;
        @Autowired
        private NacosConfigManager nacosConfigManager ;
        @Autowired
        private ObjectMapper objectMapper ;
        @Autowired
        private ApplicationEventPublisher eventPublisher ;
        private ConfigService configService ;
        @Override
        public Flux<RouteDefinition> getRouteDefinitions() {
            return Flux.fromIterable(routeDefinitions);
        }
        @Override
        public void afterPropertiesSet() throws Exception {
            // 从nacos获取routDefinition
            configService = nacosConfigManager.getConfigService();
            // 读取配置并装载
            this.initNacosConfig();
            // 添加listener,当数据变化时接收通知
            this.initNacosListener();
        }
        private void initNacosConfig(){
            try {
                String content = configService.getConfig(
                        NacosConfig.DATA_ID,
                        NacosConfig.GROUP_ID,
                        3000L
                );
                CollectionType collectionType = objectMapper.getTypeFactory()
                        .constructCollectionType(ArrayList.class, RouteDefinition.class);
                routeDefinitions = objectMapper.readValue(content, collectionType);
            }catch (NacosException e){
                log.info("nacos config NacosException ", e);
            } catch (JsonProcessingException e) {
                log.info("nacos config JsonProcessingException ", e);
            }
        }
        private void initNacosListener() throws NacosException {
            configService.addListener(
                    NacosConfig.DATA_ID,
                    NacosConfig.GROUP_ID,
                    new DataChangeListener());
        }
        class DataChangeListener implements Listener{
    
            @Override
            public Executor getExecutor() {
                return null;
            }
            @Override
            public void receiveConfigInfo(String content) {
                try {
                    log.info("gateway config change : {}", content);
                    CollectionType collectionType = objectMapper.getTypeFactory()
                            .constructCollectionType(ArrayList.class, RouteDefinition.class);
                    routeDefinitions = objectMapper.readValue(content, collectionType);
                    // 当数据发生变化后发布刷新事件,通知CachingRouteLocator需要重新加载route定义
                    eventPublisher.publishEvent(new RefreshRoutesEvent(content));
                }catch (JsonProcessingException e) {
                    log.info("nacos config JsonProcessingException ", e);
                }
            }
        }
    }
  4. 编写GatewayDynamicConfiguration配置类

    java 复制代码
    @Configuration
    public class GatewayDynamicConfiguration {
        @Bean
        @ConditionalOnProperty(value = "spring.cloud.gateway.dynamic.config.enable", matchIfMissing = true)
        public NacosRouteDefinitionLocator routeDefinitionLocator(){
            return new NacosRouteDefinitionLocator() ;
        }
    }
相关推荐
10km12 分钟前
java:Apache Commons Configuration2占位符解析异常的正确解法:${prefix:name:-default}
java·apache·configuration2·变量插值·interpolation
customer0813 分钟前
【开源免费】基于SpringBoot+Vue.JS个人博客系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
灰色人生qwer20 分钟前
SpringBoot 项目配置日志输出
java·spring boot·后端
2301_7930698230 分钟前
Spring Boot +SQL项目优化策略,GraphQL和SQL 区别,Spring JDBC 等原理辨析(万字长文+代码)
java·数据库·spring boot·sql·jdbc·orm
阿华的代码王国37 分钟前
【从0做项目】Java搜索引擎(6)& 正则表达式鲨疯了&优化正文解析
java·后端·搜索引擎·正则表达式·java项目·从0到1做项目
服务端相声演员37 分钟前
Oracle JDK、Open JDK zulu下载地址
java·开发语言
是姜姜啊!38 分钟前
java连接redis
java·redis
hhw19911239 分钟前
spring boot知识点5
java·数据库·spring boot
EQUINOX142 分钟前
lab4 CSAPP:Cachelab
java·后端·spring
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS打卡健康评测系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源