springcloud gateway动态路由

发布时间:2024年01月11日
动态每秒调用数据库,加载路由信息到路由定义(RouteDefinition)中

主要是继承? RouteDefinitionRepository接口:

@Component
@Slf4j
public class DbRouteDefinitionRepository implements RouteDefinitionRepository {

    @Resource
    private SysRouteConfMapper sys;


    @Override
    public 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);
    }

    @Override
    public Mono<Void> save(Mono<RouteDefinition> route) {
        return null;
    }

    @Override
    public 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();
    }

文章来源:https://blog.csdn.net/m0_56242825/article/details/135534175
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。