欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringCloud Gateway 和 Nacos 动态网关的相关配置

程序员文章站 2022-06-03 08:24:29
...

pom及spring-cloud、spring-cloud-alibaba版本

<properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring-boot.version>2.3.2.RELEASE</spring-boot.version>
        <spring-cloud.version>Hoxton.SR8</spring-cloud.version>
        <spring-cloud-alibaba.version>2.2.3.RELEASE</spring-cloud-alibaba.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.5.16</version>
        </dependency>
    </dependencies>

nacos 配置

routes: 
    - id: baidu
      uri: http://www.baidu.com
      predicates:
        - Path=/demo
        - RemoteAddr=127.0.0.1
      filters:
        - StripPrefix=1
    - id: content-center
      uri: lb://content-center
      predicates:
        - Path=/**
        - RemoteAddr=192.168.1.1/24

application.yml

gateway:
  dynamicRoute:
    enabled:  true
    dataType: nacos
    readTimeout: 10000
    dataId: 'xxxxx-routes.yaml'
    group: 'GATEWAY'

动态路由定义 DynamicRouteConfig 

@Configuration
@ConditionalOnProperty(prefix = "gateway.dynamicRoute", name = "enabled", havingValue = "true")
public class DynamicRouteConfig {

    @Resource
    private ApplicationEventPublisher publisher;

    /**
     * Nacos实现方式
     */
    @Configuration
    @ConditionalOnProperty(prefix = "gateway.dynamicRoute", name = "dataType", havingValue = "nacos", matchIfMissing = true)
    public class NacosDynamicRoute {
        @Resource
        private NacosConfigProperties nacosConfigProperties;

        @Bean
        public NacosRouteDefinitionRepository nacosRouteDefinitionRepository() {
            return new NacosRouteDefinitionRepository(publisher, nacosConfigProperties);
        }
    }
}

路由配置参数

@Configuration
public class GatewayRoutConfig {
    private static long DEFAULT_READ_TIMEOUT;
    private static String NACOS_DATA_ID;
    private static String NACOS_GROUP_ID;

    @Value("${gateway.dynamicRoute.dataId:gateway_platform_routes}")
    public void setNacosDataId(String dataId) {
        NACOS_DATA_ID = dataId;
    }

    @Value("${gateway.dynamicRoute.group:GATEWAY_PLATFORM}")
    public void setNacosGroupId(String group) {
        NACOS_GROUP_ID = group;
    }

    @Value("${gateway.dynamicRoute.readTimeout:10000}")
    public static void setDefaultReadTimeout(long defaultReadTimeout) {
        DEFAULT_READ_TIMEOUT = defaultReadTimeout;
    }

    public static String getNacosDataId() {
        return NACOS_DATA_ID;
    }

    public static String getNacosGroupId() {
        return NACOS_GROUP_ID;
    }

    public static long getDefaultReadTimeout() {
        return DEFAULT_READ_TIMEOUT;
    }
}

路由配置json转换实体

public class ConfigRouteDefinition {
    private List<RouteDefinition> routes;

    public List<RouteDefinition> getRoutes() {
        return routes;
    }

    public void setRoutes(List<RouteDefinition> routes) {
        this.routes = routes;
    }
}

Nacos路由定义,监听nacos配置文件变更,刷新路由策略

@RefreshScope
public class NacosRouteDefinitionRepository implements RouteDefinitionRepository {

    NacosConfigManager nacosConfigManager;

    private static final Logger logger = LoggerFactory.getLogger(NacosRouteDefinitionRepository.class);

    private ApplicationEventPublisher publisher;

    private NacosConfigProperties nacosConfigProperties;

    public NacosRouteDefinitionRepository(ApplicationEventPublisher publisher, NacosConfigProperties nacosConfigProperties) {
        this.publisher = publisher;
        this.nacosConfigProperties = nacosConfigProperties;
        this.nacosConfigManager = new NacosConfigManager(nacosConfigProperties);
        logger.info("[gateway-platform] NacosDataId: {},NacosGroupId: {}", GatewayRoutConfig.getNacosDataId(), GatewayRoutConfig.getNacosGroupId());
        this.addListener();
    }

    @Override
    public Flux<RouteDefinition> getRouteDefinitions() {
        try {
            String content = nacosConfigManager.getConfigService().getConfig(GatewayRoutConfig.getNacosDataId(), GatewayRoutConfig.getNacosGroupId(), GatewayRoutConfig.getDefaultReadTimeout());
            logger.info("[gateway-platform]获取网关当前配置:{}", content);
            List<RouteDefinition> routeDefinitions = getListByStr(content);
            return Flux.fromIterable(routeDefinitions);
        } catch (NacosException e) {
            logger.error("getRouteDefinitions by nacos error", e);
        }
        return Flux.fromIterable(CollUtil.newArrayList());
    }

    /**
     * 添加Nacos监听
     */
    private void addListener() {
        try {
            nacosConfigManager.getConfigService().addListener(GatewayRoutConfig.getNacosDataId(), GatewayRoutConfig.getNacosGroupId(), new Listener() {
                @Override
                public Executor getExecutor() {
                    return null;
                }

                @Override
                public void receiveConfigInfo(String configInfo) {
                    publisher.publishEvent(new RefreshRoutesEvent(this));
                }
            });
        } catch (NacosException e) {
            logger.error("nacos-addListener-error", e);
        }
    }

    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {
        return null;
    }

    @Override
    public Mono<Void> delete(Mono<String> routeId) {
        return null;
    }

    private List<RouteDefinition> getListByStr(String content) {
        if (StrUtil.isNotEmpty(content)) {
            Yaml yaml = new Yaml();
            ConfigRouteDefinition configRouteDefinition = yaml.loadAs(content, ConfigRouteDefinition.class);
            return configRouteDefinition.getRoutes();
        }
        return Collections.emptyList();
    }
}

 

相关标签: Spring Cloud