动态每秒调用数据库,加载路由信息到路由定义(RouteDefinition)中
主要是继承 RouteDefinitionRepository接口:
@Component
@Slf4j
public class DbRouteDefinitionRepository implements RouteDefinitionRepository {@Resourceprivate SysRouteConfMapper sys;@Overridepublic Flux<RouteDefinition> getRouteDefinitions() {List<RouteDefinition> routeDefinitions = new ArrayList<>();
//获取数据库路由信息List<SysRouteConf> gatewayRouteList = sysRouteConfMapper.selectList();
//路由信息转为路由定义gatewayRouteList.forEach(gatewayRoute -> {RouteDefinition routeDefinition = JSONObject.parseObject(gatewayRoute.toString(), RouteDefinition.class);routeDefinitions.add(routeDefinition);});
//存入内存中return Flux.fromIterable(routeDefinitions);}@Overridepublic Mono<Void> save(Mono<RouteDefinition> route) {return null;}@Overridepublic Mono<Void> delete(Mono<String> routeId) {return null;}
}
获取请求的路由信息
主要从RouteLocator的三个实现类中获取
//获取路径
protected String getUrl() {AtomicReference<String> url = new AtomicReference<>("");RouteLocator cachedCompositeRouteLocator = SpringUtils.getBean("cachedCompositeRouteLocator");Flux<Route> identification = cachedCompositeRouteLocator.getRoutes().filter(route -> {return route.getId().equals("identification");});identification.subscribe(result -> {URI uri = result.getUri();if (uri != null && ("lb".equals(uri.getScheme()))) {ServiceInstance router = loadBalancer.choose("identification");url.set(router.getHost() + ":" + router.getPort());}if (uri != null && ("http".equals(uri.getScheme()) || "https".equals(uri.getScheme()))) {url.set(uri.getHost() + ":" + uri.getPort());}});return url.get();}