详解Spring Cloud Gateway 数据库存储路由信息的扩展方案

时间:2022-05-23 06:46:13

动态路由背景

​ 无论你在使用zuul还是spring cloud gateway 的时候,官方文档提供的方案总是基于配置文件配置的方式

例如:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 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 数据库存储路由信息的扩展方案

spring cloud gateway 路由加载源码

  1. dispatcherhandler 接管用户请求
  2. routepredicatehandlermapping 路由匹配
    1. 根据routelocator获取 routedefinitionlocator
    2. 返回多个routedefinitionlocator.getroutedefinitions()的路由定义信息
  3. filteringwebhandler执行路由定义中的filter 最后路由到具体的业务服务中

详解Spring Cloud Gateway 数据库存储路由信息的扩展方案

spring cloud gateway 默认动态路由实现

gatewaycontrollerendpoint 基于actuate端点的默认实现,支持jvm 级别的动态路由,不能序列化存储

详解Spring Cloud Gateway 数据库存储路由信息的扩展方案

?
1
2
3
4
5
6
7
8
9
10
11
// 上图动态路由的信息保存的默认实现是基于内存的实现
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?

  • spring cloud gateway 基于webflux 背压,暂时不支持mysql 数据库
  • redis-reactive 支持 spring cloudgateway 的背压,同时还可以实现分布式,高性能

扩展思路

详解Spring Cloud Gateway 数据库存储路由信息的扩展方案

  1. 增加一个路由管理模块,参考gatewaycontrollerendpoint实现,启动时加载数据库中配置文件到redis
  2. 网关模块重写routedefinitionrepository,getroutedefinitions()取redis中读取即可实现
  3. 前端配合 json-view 类似插件,直接修改展示。

具体实现

路由管理模块核心处理逻辑,获取路由和更新路由

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
 * @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();
  }
}

网关自定义redisroutedefinitionrepository

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@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.库表定义

详解Spring Cloud Gateway 数据库存储路由信息的扩展方案

详解Spring Cloud Gateway 数据库存储路由信息的扩展方案

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://segmentfault.com/a/1190000016967513