从零开始SpringCloud Alibaba实战(39)——Spring Cloud Gateway动态路由实现

前文介绍了多种路由配置方式,它们存在一个共同问题:路由配置变更后必须重启Gateway应用才能生效,这样不适合生产环境!

引入服务网关Gateway
如何让变动后的路由立即生效,而无需重启应用呢?这就是今天的主题:动态路由

思路

  • 这里提前将设计思路捋清楚,总的来说就是将配置放在nacos上,写个监听器监听nacos上配置的变化,将变化后的配置更新到Gateway应用的进程内:
    上述思路体现在代码中就是下面三个类:
  • 将操作路由的代码封装到名为RouteOperator的类中,用此类来删除和增加进程内的路由
  • 做一个配置类RouteOperatorConfig,可以将RouteOperator作为bean注册在spring环境中
  • 监听nacos上的路由配置文件,一旦有变化就取得最新配置,然后调用RouteOperator的方法更新进程内的路由,这些监听nacos配置和调用RouteOperator的代码都放RouteConfigListener类中

编码

在网关工程下编写如下类:

负责处理进程内路由配置的类是RouteOperator



import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class RouteOperator {
    private ObjectMapper objectMapper;

    private RouteDefinitionWriter routeDefinitionWriter;

    private ApplicationEventPublisher applicationEventPublisher;

    private static final List routeList = new ArrayList<>();

    public RouteOperator(ObjectMapper objectMapper, RouteDefinitionWriter routeDefinitionWriter, ApplicationEventPublisher applicationEventPublisher) {
        this.objectMapper = objectMapper;
        this.routeDefinitionWriter = routeDefinitionWriter;
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * 清理集合中的所有路由,并清空集合
     */
    private void clear() {
        // 全部调用API清理掉
        routeList.stream().forEach(id -> routeDefinitionWriter.delete(Mono.just(id)).subscribe());
        // 清空集合
        routeList.clear();
    }

    /**
     * 新增路由
     * @param routeDefinitions
     */
    private void add(List routeDefinitions) {

        try {
            routeDefinitions.stream().forEach(routeDefinition -> {
                routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
                routeList.add(routeDefinition.getId());
            });
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 发布进程内通知,更新路由
     */
    private void publish() {
        applicationEventPublisher.publishEvent(new RefreshRoutesEvent(routeDefinitionWriter));
    }

    /**
     * 更新所有路由信息
     * @param configStr
     */
    public void refreshAll(String configStr) {
        log.info("start refreshAll : {}", configStr);
        // 无效字符串不处理
        if (!StringUtils.hasText(configStr)) {
            log.error("invalid string for route config");
            return;
        }

        // 用Jackson反序列化
        List routeDefinitions = null;

        try {
            routeDefinitions = objectMapper.readValue(configStr, new TypeReference>(){});
        } catch (JsonProcessingException e) {
            log.error("get route definition from nacos string error", e);
        }

        // 如果等于null,表示反序列化失败,立即返回
        if (null==routeDefinitions) {
            return;
        }

        // 清理掉当前所有路由
        clear();

        // 添加最新路由
        add(routeDefinitions);

        // 通过应用内消息的方式发布
        publish();

        log.info("finish refreshAll");
    }
}

可见整个配置是字符串类型的,用了Jackson的ObjectMapper进行反序列化(注意,前面的实战中配置文件都是yml格式,但本例中是JSON,稍后在nacos上配置要用JSON格式),然后路由配置的处理主要是RouteDefinitionWriter类型的bean完成的,为了让配置立即生效,还要用applicationEventPublisher发布进程内消息:

配置类RouteOperatorConfig.java,将实例化后的RouteOperator注册到spring环境中



import com.bolingcavalry.gateway.service.RouteOperator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RouteOperatorConfig {
    @Bean
    public RouteOperator routeOperator(ObjectMapper objectMapper,
                                       RouteDefinitionWriter routeDefinitionWriter,
                                       ApplicationEventPublisher applicationEventPublisher) {

        return new RouteOperator(objectMapper,
                routeDefinitionWriter,
                applicationEventPublisher);
    }
}


nacos的监听类RouteConfigListener

关键技术点是ConfigService.addListener,用于添加监听,里面就是配置发生变化后更新路由的逻辑,另外还有很重要的一步:立即调用getConfig方法取得当前配置,刷新当前进程的路由配置



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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;

@Component
@Slf4j
public class RouteConfigListener {

    private String dataId = "gateway-json-routes";

    private String group = "DEFAULT_GROUP";

    @Value("${spring.cloud.nacos.config.server-addr}")
    private String serverAddr;

    @Autowired
    RouteOperator routeOperator;

    @PostConstruct
    public void dynamicRouteByNacosListener() throws NacosException {

        ConfigService configService = NacosFactory.createConfigService(serverAddr);

        // 添加监听,nacos上的配置变更后会执行
        configService.addListener(dataId, group, new Listener() {

            public void receiveConfigInfo(String configInfo) {
                // 解析和处理都交给RouteOperator完成
                routeOperator.refreshAll(configInfo);
            }

            public Executor getExecutor() {
                return null;
            }
        });

        // 获取当前的配置
        String initConfig = configService.getConfig(dataId, group, 5000);

        // 立即更新
        routeOperator.refreshAll(initConfig);
    }
}

RouteConfigListener.java中还有一处要记下来,那就是dataId变量的值gateway-json-routes,这是nacos上配置文件的名字

nacos上增加两个配置;

第一个配置名为gateway-dynamic-by-nacos,内容如下:

server:
  port: 8086

# 暴露端点
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always

第二个配置名为gateway-json-routes,格式要选择JSON

[
    {
        "id": "path_route_addr",
        "uri": "http://127.0.0.1:8082",
        "predicates":[
            {
                "name": "Path",
                "args": {
                    "pattern": "/hello/**"
                }
            }
        ]
    }
    ,
    {
        "id": "path_route_lb",
        "uri": "lb://provider-hello",
        "predicates":[
            {
                "name": "Path",
                "args": {
                    "pattern": "/lbtest/**"
                }
            }
        ]
    }
]


依赖了spring-boot-starter-actuator库,并且配置文件中也添加了相关配置,我们还可以查看SpringBoot应用内部的配置情况,用浏览器访问http://localhost:8086/actuator/gateway/routes

你可能感兴趣的:(项目实战)