动态路由大致分为3个步骤

  1. 首先查询数据库配置,表结构可以这样设计
create table gateway_route
(
    id           bigint                  not null comment 'ID'
        primary key,
    uri          varchar(255) default '' not null comment '转发URI',
    path         varchar(255) default '' not null comment 'Path断言',
    strip_prefix int          default 0  not null comment '路径删除节数',
    order_val    int          default 0  not null comment '优先级(值越小越高)',
    skip_timeout int          default 0  null comment '0正常1跳过超时',
    state        int          default 0  null comment '0正常1禁用'
)
    comment '网关路由表';

INSERT INTO gateway_route (id, uri, path, strip_prefix, order_val,  skip_timeout) VALUES (1, 'lb://spring-demo', '/api-demo/**', 1, 0, 0, 0);

  1. 创建路由(更新、删除)
    2.1. 创建RouteDefinition,把数据库配置set进去,先添加List<PredicateDefinition>
	List<PredicateDefinition> predicates = new ArrayList<>();
	PredicateDefinition predicateDefinition = new PredicateDefinition();
	predicateDefinition.setName("Path");
	predicateDefinition.addArg("patterns", record.getPath().trim());
	predicates.add(predicateDefinition);

name中的Path对应数据库path,也就是/api-demo/**


  2.2. 创建 List<FilterDefinition>FilterDefinitionname有很多属性,详细参考下方引用文档,挑几个常用的记录一下。

StripPrefix

把请求中的前n个路径去掉,以/分隔。

	List<FilterDefinition> filters = new ArrayList<>();

	FilterDefinition filter = new FilterDefinition();
	filter.setName("StripPrefix");
	filter.addArg("parts", record.getStripPrefix().toString());
	filters.add(filter);

解释:上面的record.getStripPrefix()对应数据库strip_prefix,意思是截取path1位前缀,如请求/api-demo/api/request 被截取为 /api/request

Hystrix

配置熔断和降级策略,这个很好理解。

	FilterDefinition hystrix = new FilterDefinition();

	hystrix.setName("Hystrix");
	hystrix.addArg("name", "fallbackCmd");
	// 熔断的URL
	hystrix.addArg("fallbackUri", "forward:/error/fallback";
	filters.add(hystrix);
RewritePath

用于重写路径,可以修改请求的路径,并将其重定向到新的路径。注意是使用Java正则表达式。

	FilterDefinition rewritePath = new FilterDefinition();
	rewritePath.setName("RewritePath");
	// /api-demo/** -> /api-demo/
	String endPath = record.getPath().replace("**", "");

	rewritePath.addArg("regexp", endPath + "(?<segment>.*)");
	rewritePath.addArg("replacement", endPath + "${segment}");
	filters.add(rewritePath);
  1. 刷新路由
    发布一个事件,类型为RefreshRoutesEvent,监听类为org.springframework.cloud.gateway.route.CachingRouteLocator

Spring Cloud Gateway官方文档

Logo

一起探索未来云端世界的核心,云原生技术专区带您领略创新、高效和可扩展的云计算解决方案,引领您在数字化时代的成功之路。

更多推荐