网站开发用什么开发,wordpress模板UI,班级网站建设模板,在线手机网站预览我们来设定一个场景: 假设我们的应用仅仅让age在(min,max)之间的人来访问。
第1步#xff1a;在配置文件中,添加一个Age的断言配置
spring:
application:name: api-gateway
cloud:nacos:discovery:server-addr: 127.0.0.1:8848gateway:discovery:locator:enabled: trueroute…我们来设定一个场景: 假设我们的应用仅仅让age在(min,max)之间的人来访问。
第1步在配置文件中,添加一个Age的断言配置
spring:
application:name: api-gateway
cloud:nacos:discovery:server-addr: 127.0.0.1:8848gateway:discovery:locator:enabled: trueroutes:- id: product-routeuri: lb://service-productpredicates:- Path/product-serv/**- Age18,60 # 限制年龄只有在18到60岁之间的人能访问filters:- StripPrefix1
第2步自定义一个断言工厂, 实现断言方法
package com.itheima.predicates;
//泛型 用于接收一个配置类,配置类用于接收中配置文件中的配置
Component
public class AgeRoutePredicateFactoryextends AbstractRoutePredicateFactoryAgeRoutePredicateFactory.Config {public AgeRoutePredicateFactory() {super(AgeRoutePredicateFactory.Config.class);}//用于从配置文件中获取参数值赋值到配置类中的属性上Overridepublic ListString shortcutFieldOrder() {//这里的顺序要跟配置文件中的参数顺序一致return Arrays.asList(minAge, maxAge);}//断言Overridepublic PredicateServerWebExchange apply(AgeRoutePredicateFactory.Config
config) {return new PredicateServerWebExchange() {Overridepublic boolean test(ServerWebExchange serverWebExchange) {//从serverWebExchange获取传入的参数String ageStr serverWebExchange.getRequest().getQueryParams().getFirst(age);if (StringUtils.isNotEmpty(ageStr)) {int age Integer.parseInt(ageStr);return age config.getMinAge() age config.getMaxAge();}return true;}};}
}
//自定义一个配置类, 用于接收配置文件中的参数
Data
class Config {private int minAge;private int maxAge;
}
第4步启动测试
#测试发现当age在(20,60)可以访问,其它范围不能访问
http://localhost:7000/product-serv/product/1?age30
http://localhost:7000/product-serv/product/1?age10