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() ;
        }
    }
相关推荐
小鑫记得努力3 分钟前
Java类和对象(下篇)
java
binishuaio6 分钟前
Java 第11天 (git版本控制器基础用法)
java·开发语言·git
zz.YE8 分钟前
【Java SE】StringBuffer
java·开发语言
老友@8 分钟前
aspose如何获取PPT放映页“切换”的“持续时间”值
java·powerpoint·aspose
wrx繁星点点24 分钟前
状态模式(State Pattern)详解
java·开发语言·ui·设计模式·状态模式
Upaaui26 分钟前
Aop+自定义注解实现数据字典映射
java
zzzgd81627 分钟前
easyexcel实现自定义的策略类, 最后追加错误提示列, 自适应列宽,自动合并重复单元格, 美化表头
java·excel·表格·easyexcel·导入导出
友善的鸡蛋28 分钟前
解决:使用EasyExcel导入Excel模板时出现数据导入不进去的问题
java·easyexcel·excel导入
星沁城28 分钟前
240. 搜索二维矩阵 II
java·线性代数·算法·leetcode·矩阵
NoneCoder41 分钟前
Java企业级开发系列(1)
java·开发语言·spring·团队开发·开发