Route 的处理器与定制
RouteHandler 是负责路由处理的接口。
public interface RouteHandler extends ExHandler {
//架构支持
String[] schemas();
}
@FunctionalInterface
public interface ExHandler {
//处理
Completable handle(ExContext ctx);
}
1、内置的处理器
处理器 | 支持协议头 | 说明与示例 |
---|---|---|
HttpRouteHandler | http:// , https:// | Http 路由处理器 |
LbRouteHandler | lb:// | Lb(负载均衡) 路由处理器,找到节点后重新查找对应的路由处理器 |
更多的协议头,可以按需定制。
2、配置示例
solon.cloud.gateway:
routes: #!必选
- id: demo
target: "http://localhost:8080" # 或 "lb://user-service"
predicates: #?可选
- "Path=/demo/**"
filters: #?可选
- "StripPrefix=1"
3、定制示例
public class LbRouteHandler implements RouteHandler {
@Override
public String[] schemas() {
return new String[]{"lb"};
}
@Override
public Completable handle(ExContext ctx) {
//构建新的目标
URI targetUri = ctx.targetNew();
String tmp = LoadBalance.get(targetUri.getHost()).getServer(targetUri.getPort());
if (tmp == null) {
throw new StatusException("The target service does not exist", 404);
}
//配置新目标
targetUri = URI.create(tmp);
ctx.targetNew(targetUri);
//重新查找处理器
RouteHandler handler = RouteFactoryManager.getHandler(targetUri.getScheme());
if (handler == null) {
throw new StatusException("The target handler does not exist", 404);
}
return handler.handle(ctx);
}
}