SpringCloudGateway資料庫儲存路由資訊的擴充套件方案

gggggwww發表於2018-11-09

動態路由背景

​ 無論你在使用Zuul還是Spring Cloud Gateway 的時候,官方文件提供的方案總是基於配置檔案配置的方式

例如:

  # zuul 的配置形式
  routes:
    pig-auth:
      path: /auth/**
      serviceId: pig-auth
      stripPrefix: true
  # gateway 的配置形式
  routes:
  - id: pigx-auth
      uri: lb://pigx-auth
    predicates:
    - Path=/auth/**
    filters:
    - ValidateCodeGatewayFilter

配置更改需要重啟服務,不能滿足實際生產過程中的動態重新整理、實時變更的業務需求。

​ 基於以上分析 pig已經提供了基於Zuul版本的動態路由功能,附Git 地址傳送門,效果如下圖可以實時配置修改重新整理。

Spring Cloud Gateway 路由載入原始碼

  1. DispatcherHandler 接管使用者請求
  2. RoutePredicateHandlerMapping 路由匹配

    1. 根據RouteLocator獲取 RouteDefinitionLocator
    2. 返回多個RouteDefinitionLocator.getRouteDefinitions()的路由定義資訊
  3. FilteringWebHandler執行路由定義中的filter 最後路由到具體的業務服務中

Spring Cloud Gateway 預設動態路由實現

GatewayControllerEndpoint 基於actuate端點的預設實現,支援JVM 級別的動態路由,不能序列化儲存

// 上圖動態路由的資訊儲存的預設實現是基於記憶體的實現
public class InMemoryRouteDefinitionRepository implements RouteDefinitionRepository {
    private final Map<String, RouteDefinition> routes = synchronizedMap(new LinkedHashMap<String, RouteDefinition>());
    @Override
    public Mono<Void> save(Mono<RouteDefinition> route){}
    @Override
    public Mono<Void> delete(Mono<String> routeId){}

    @Override
    public Flux<RouteDefinition> getRouteDefinitions(){}
}

擴充套件基於Mysql + Redis儲存分散式動態元件

為什麼使用Mysql的同時,又要使用Redis?

  1. spring cloud gateway 基於webflux 背壓,暫時不支援mysql 資料庫
  2. Redis-reactive 支援 spring cloudgateway 的背壓,同時還可以實現分散式,高效能

擴充套件思路

  1. 增加一個路由管理模組,參考GatewayControllerEndpoint實現,啟動時載入資料庫中配置檔案到Redis
  2. 閘道器模組重寫RouteDefinitionRepository,getRouteDefinitions()取Redis中讀取即可實現
  3. 前端配合 json-view 類似外掛,直接修改展示。

具體實現

  1. 路由管理模組核心處理邏輯,獲取路由和更新路由
/**
 * @author lengleng
 * @date 2018年11月06日10:27:55
 * <p>
 * 動態路由處理類
 */
@Slf4j
@AllArgsConstructor
@Service("sysRouteConfService")
public class SysRouteConfServiceImpl extends ServiceImpl<SysRouteConfMapper, SysRouteConf> implements SysRouteConfService {
    private final RedisTemplate redisTemplate;
    private final ApplicationEventPublisher applicationEventPublisher;

    /**
     * 獲取全部路由
     * <p>
     * RedisRouteDefinitionWriter.java
     * PropertiesRouteDefinitionLocator.java
     *
     * @return
     */
    @Override
    public List<SysRouteConf> routes() {
        SysRouteConf condition = new SysRouteConf();
        condition.setDelFlag(CommonConstant.STATUS_NORMAL);
        return baseMapper.selectList(new EntityWrapper<>(condition));
    }

    /**
     * 更新路由資訊
     *
     * @param routes 路由資訊
     * @return
     */
    @Override
    public Mono<Void> editRoutes(JSONArray routes) {
        // 清空Redis 快取
        Boolean result = redisTemplate.delete(CommonConstant.ROUTE_KEY);
        log.info("清空閘道器路由 {} ", result);

        // 遍歷修改的routes,儲存到Redis
        List<RouteDefinitionVo> routeDefinitionVoList = new ArrayList<>();
        routes.forEach(value -> {
            log.info("更新路由 ->{}", value);
            RouteDefinitionVo vo = new RouteDefinitionVo();
            Map<String, Object> map = (Map) value;

            Object id = map.get("routeId");
            if (id != null) {
                vo.setId(String.valueOf(id));
            }

            Object predicates = map.get("predicates");
            if (predicates != null) {
                JSONArray predicatesArray = (JSONArray) predicates;
                List<PredicateDefinition> predicateDefinitionList =
                    predicatesArray.toList(PredicateDefinition.class);
                vo.setPredicates(predicateDefinitionList);
            }

            Object filters = map.get("filters");
            if (filters != null) {
                JSONArray filtersArray = (JSONArray) filters;
                List<FilterDefinition> filterDefinitionList
                    = filtersArray.toList(FilterDefinition.class);
                vo.setFilters(filterDefinitionList);
            }

            Object uri = map.get("uri");
            if (uri != null) {
                vo.setUri(URI.create(String.valueOf(uri)));
            }

            Object order = map.get("order");
            if (order != null) {
                vo.setOrder(Integer.parseInt(String.valueOf(order)));
            }

            redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(RouteDefinitionVo.class));
            redisTemplate.opsForHash().put(CommonConstant.ROUTE_KEY, vo.getId(), vo);
            routeDefinitionVoList.add(vo);
        });

        // 邏輯刪除全部
        SysRouteConf condition = new SysRouteConf();
        condition.setDelFlag(CommonConstant.STATUS_NORMAL);
        this.delete(new EntityWrapper<>(condition));

        //插入生效路由
        List<SysRouteConf> routeConfList = routeDefinitionVoList.stream().map(vo -> {
            SysRouteConf routeConf = new SysRouteConf();
            routeConf.setRouteId(vo.getId());
            routeConf.setFilters(JSONUtil.toJsonStr(vo.getFilters()));
            routeConf.setPredicates(JSONUtil.toJsonStr(vo.getPredicates()));
            routeConf.setOrder(vo.getOrder());
            routeConf.setUri(vo.getUri().toString());
            return routeConf;
        }).collect(Collectors.toList());
        this.insertBatch(routeConfList);
        log.debug("更新閘道器路由結束 ");

        this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
        return Mono.empty();
    }
}
  1. 閘道器自定義RedisRouteDefinitionRepository

    @Slf4j
    @Component
    @AllArgsConstructor
    public class RedisRouteDefinitionWriter implements RouteDefinitionRepository {
       private final RedisTemplate redisTemplate;
    
       @Override
       public Mono<Void> save(Mono<RouteDefinition> route) {
           return route.flatMap(r -> {
               RouteDefinitionVo vo = new RouteDefinitionVo();
               BeanUtils.copyProperties(r, vo);
               log.info("儲存路由資訊{}", vo);
               redisTemplate.opsForHash().put(CommonConstant.ROUTE_KEY, r.getId(), vo);
               return Mono.empty();
           });
       }
       @Override
       public Mono<Void> delete(Mono<String> routeId) {
           routeId.subscribe(id -> {
               log.info("刪除路由資訊{}", id);
               redisTemplate.opsForHash().delete(CommonConstant.ROUTE_KEY, id);
           });
           return Mono.empty();
       }
    
       @Override
       public Flux<RouteDefinition> getRouteDefinitions() {
           redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(RouteDefinitionVo.class));
           List<RouteDefinitionVo> values = redisTemplate.opsForHash().values(CommonConstant.ROUTE_KEY);
           List<RouteDefinition> definitionList = new ArrayList<>();
           values.forEach(vo -> {
               RouteDefinition routeDefinition = new RouteDefinition();
               BeanUtils.copyProperties(vo, routeDefinition);
               definitionList.add(vo);
           });
           log.debug("redis 中路由定義條數: {}, {}", definitionList.size(), definitionList);
           return Flux.fromIterable(definitionList);
       }
    }

3.庫表定義


相關文章