springcloud gateway动态路由

动态每秒调用数据库,加载路由信息到路由定义(RouteDefinition)中

主要是继承  RouteDefinitionRepository接口:

如果项目没有自定义的RouteDefinitionRepository 则会加载InMemoryRouteDefinitionRepository
默认将加载的规则存放在内存,加载application.properties文件中配置的路由规则,InMemory加载内存中配置的路由规则
Application启动的时候内存中是没有路由规则的且Application关闭的时候内存中保存的路由规则也会丢失
我们可以通过自定义RouteDefinitionRepository类替换掉InMemoryRouteDefinitionRepository
实现将路由规则保存到数据库中
 

@Component
@Slf4j
public class DbRouteDefinitionRepository implements RouteDefinitionRepository {

    @Resource
    private SysRouteConfMapper sys;


    @Override
    public Flux getRouteDefinitions() {
        List routeDefinitions = new ArrayList<>();
//获取数据库路由信息
        List gatewayRouteList = sysRouteConfMapper.selectList();
//路由信息转为路由定义
        gatewayRouteList.forEach(gatewayRoute -> {
            RouteDefinition routeDefinition = JSONObject.parseObject(gatewayRoute.toString(), RouteDefinition.class);
            routeDefinitions.add(routeDefinition);
        });
//存入内存中
        return Flux.fromIterable(routeDefinitions);
    }

    @Override
    public Mono save(Mono route) {
        return null;
    }

    @Override
    public Mono delete(Mono routeId) {
        return null;
    }
}
获取请求的路由信息

主要从RouteLocator的三个实现类中获取

//获取路径

    protected String getUrl() {
        AtomicReference url = new AtomicReference<>("");
        RouteLocator cachedCompositeRouteLocator = SpringUtils.getBean("cachedCompositeRouteLocator");
        Flux 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();
    }

相关流程见此链接:

【Spring Cloud】Gateway —— RouteLocator RouteDefinitionLocator FilteringWebHandler_spring gateway filteringwebhandler-CSDN博客

你可能感兴趣的:(spring,cloud,gateway,spring,boot)