java读取路由列表信息_详解Spring Cloud Gateway 数据库存储路由信息的扩展方案

  • Post author:
  • Post category:java


动态路由背景

​ 无论你在使用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 地址传送门,效果如下图可以实时配置修改刷新。

40699b0bb34ef4749ac637205c65e426.png

spring cloud gateway 路由加载源码

dispatcherhandler 接管用户请求

routepredicatehandlermapping 路由匹配

根据routelocator获取 routedefinitionlocator

返回多个routedefinitionlocator.getroutedefinitions()的路由定义信息

filteringwebhandler执行路由定义中的filter 最后路由到具体的业务服务中

d25de43170bb7512ee32eb1219fcf114.png

spring cloud gateway 默认动态路由实现

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

bf736ef07bc768e3048b2c75389f274c.png

// 上图动态路由的信息保存的默认实现是基于内存的实现

public class inmemoryroutedefinitionrepository implements routedefinitionrepository {

private final map routes = synchronizedmap(new linkedhashmap());

@override

public mono save(mono route){}

@override

public mono delete(mono routeid){}

@override

public flux getroutedefinitions(){}

}

扩展基于mysql + redis存储分布式动态组件

为什么使用mysql的同时,又要使用redis?

spring cloud gateway 基于webflux 背压,暂时不支持mysql 数据库

redis-reactive 支持 spring cloudgateway 的背压,同时还可以实现分布式,高性能

扩展思路

ef338e8c651880312d4005cc5c912cea.png

增加一个路由管理模块,参考gatewaycontrollerendpoint实现,启动时加载数据库中配置文件到redis

网关模块重写routedefinitionrepository,getroutedefinitions()取redis中读取即可实现

前端配合 json-view 类似插件,直接修改展示。

具体实现

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

/**

* @author lengleng

* @date 2018年11月06日10:27:55

*

* 动态路由处理类

*/

@slf4j

@allargsconstructor

@service(“sysrouteconfservice”)

public class sysrouteconfserviceimpl extends serviceimpl implements sysrouteconfservice {

private final redistemplate redistemplate;

private final applicationeventpublisher applicationeventpublisher;

/**

* 获取全部路由

*

* redisroutedefinitionwriter.java

* propertiesroutedefinitionlocator.java

*

* @return

*/

@override

public list routes() {

sysrouteconf condition = new sysrouteconf();

condition.setdelflag(commonconstant.status_normal);

return basemapper.selectlist(new entitywrapper<>(condition));

}

/**

* 更新路由信息

*

* @param routes 路由信息

* @return

*/

@override

public mono editroutes(jsonarray routes) {

// 清空redis 缓存

boolean result = redistemplate.delete(commonconstant.route_key);

log.info(“清空网关路由 {} “, result);

// 遍历修改的routes,保存到redis

list routedefinitionvolist = new arraylist<>();

routes.foreach(value -> {

log.info(“更新路由 ->{}”, value);

routedefinitionvo vo = new routedefinitionvo();

map 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 predicatedefinitionlist =

predicatesarray.tolist(predicatedefinition.class);

vo.setpredicates(predicatedefinitionlist);

}

object filters = map.get(“filters”);

if (filters != null) {

jsonarray filtersarray = (jsonarray) filters;

list 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 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

@slf4j

@component

@allargsconstructor

public class redisroutedefinitionwriter implements routedefinitionrepository {

private final redistemplate redistemplate;

@override

public mono save(mono 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 delete(mono routeid) {

routeid.subscribe(id -> {

log.info(“删除路由信息{}”, id);

redistemplate.opsforhash().delete(commonconstant.route_key, id);

});

return mono.empty();

}

@override

public flux getroutedefinitions() {

redistemplate.sethashvalueserializer(new jackson2jsonredisserializer<>(routedefinitionvo.class));

list values = redistemplate.opsforhash().values(commonconstant.route_key);

list 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.库表定义

a4e49e419730fa1929a22a4b3680d6be.png

1e40c9836bd6354cdf3dd7fc85e1a2e3.png

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

希望与广大网友互动??

点此进行留言吧!



版权声明:本文为weixin_42514540原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。