动态路由背景
站在用户的角度思考问题,与客户深入沟通,找到吉安网站设计与吉安网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站制作、成都网站建设、企业官网、英文网站、手机端网站、网站推广、域名申请、雅安服务器托管、企业邮箱。业务覆盖吉安地区。
无论你在使用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 路由加载源码
Spring Cloud Gateway 默认动态路由实现
GatewayControllerEndpoint 基于actuate端点的默认实现,支持JVM 级别的动态路由,不能序列化存储
// 上图动态路由的信息保存的默认实现是基于内存的实现 public class InMemoryRouteDefinitionRepository implements RouteDefinitionRepository { private final Maproutes = synchronizedMap(new LinkedHashMap ()); @Override public Mono save(Mono route){} @Override public Mono delete(Mono routeId){} @Override public Flux getRouteDefinitions(){} }
扩展基于MySQL + redis存储分布式动态组件
为什么使用Mysql的同时,又要使用Redis?
扩展思路
具体实现
路由管理模块核心处理逻辑,获取路由和更新路由
/** * @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 Monosave(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.库表定义
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。