动态每秒调用数据库,加载路由信息到路由定义(RouteDefinition)中
主要是继承 RouteDefinitionRepository接口:
如果项目没有自定义的RouteDefinitionRepository 则会加载InMemoryRouteDefinitionRepository
默认将加载的规则存放在内存,加载application.properties文件中配置的路由规则,InMemory加载内存中配置的路由规则
Application启动的时候内存中是没有路由规则的且Application关闭的时候内存中保存的路由规则也会丢失
我们可以通过自定义RouteDefinitionRepository类替换掉InMemoryRouteDefinitionRepository
实现将路由规则保存到数据库中
java
@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的三个实现类中获取
//获取路径
java
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();
}
相关流程见此链接: