Spring Cloud Gateway动态加载路由和路由Filter配置

动态路由大致分为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官方文档

  • 12
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值