做现货黄金看什么网站,做网站郑州公司,如何注册公众号,单位网站开发费用入什么费用1.网关过滤器介绍
网关过滤器的用途一般是修改请求或响应信息,例如编解码、Token验证、流量复制等
官方文档地址:Spring Cloud Gateway
网关过滤器分为GloablFilter、GatewayFilter及DefaultFilter
过滤器的执行顺序由Order决定,Order值越小,优先级越高,越先执行
1.1…1.网关过滤器介绍
网关过滤器的用途一般是修改请求或响应信息,例如编解码、Token验证、流量复制等
官方文档地址:Spring Cloud Gateway
网关过滤器分为GloablFilter、GatewayFilter及DefaultFilter
过滤器的执行顺序由Order决定,Order值越小,优先级越高,越先执行
1.1 GlobalFilter
自定义的GlobalFilter一般需要实现GlobalFilter和Order接口,官网的示例代码如下:
@Bean
public GlobalFilter customFilter() {return new CustomGlobalFilter();
}@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {@Overridepublic MonoVoid filter(ServerWebExchange exchange, GatewayFilterChain chain) {log.info("custom global filter");return chain.filter(exchange);}@Overridepublic int getOrder() {return -1;}
}
配置了全局过滤器之后,当接收到匹配路由的请求时,会执行过滤
1.2 DefaultFilter
DefaultFilter也可以作用于所有路由,配置方式如下:
spring:cloud:gateway:default-filters:- AddRequestHeader=X-Request-Id,123456
1.3 GatewayFilter
官方提供了许多现成的GatewayFilter,可以直接使用,具体参考官方文档,RewritePath示例如下:
spring:cloud:gateway:routes:- id: rewritepath_routeuri: https://example.orgpredicates:- Path=/red/**filters:- RewritePath=/red/?(?segment.*), /$\{segment}
很多场景下需要自定义GatewayFilter,一般可以自定义GatewayFilterFactory继承自AbstractGatewayFilterFactory,名称必须由filter名称+GatewayFilterFactory组成,然后再实现apply方法中返回自定义的GatewayFilter对象,该对象一般需要实现GatewayFilter及Order接口,示例如下:
@Component
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactoryCustomConfig {public CustomGatewayFilterFactory() {super(CustomConfig.class);}@Overridepublic GatewayFilter apply(CustomConfig config) {return new CustomGatewayFilter(config);}
}
@Getter
@Setter
public class CustomConfig {private String desc;
}
@Slf4j
public class CustomGatewayFilter implements GatewayFilter, Ordered {// 配置类,对应yaml中的args部分private CustomConfig config;public CallbackGatewayFilter(CallbackConfig config) {this.config = config;}@Overridepublic MonoVoid filter(ServerWebExchange exchange, GatewayFilterChain chain) {// 执行过滤逻辑log.info("custom gateway filter:{}", config.getDesc);return chain.filter(exchange);}@Overridepublic int getOrder() {return 0;}
}
在配置文件中使用时,通过name属性指定filter名称,可以通过args传入自定义配置参数,这些参数会被封装到配置类CustomConfig中,例如:
spring:cloud:gateway:routes:- id: oldServeruri: lb://oldServerpredicates:- Path=/MyServer/**filters:# 通过name+GatewayFilterFactory找到对应的过滤器- name: Custom# 自定义过滤器配置args:desc: "this is a custom filter"
2.实际开发中的应用
2.1 缓存请求体全局过滤器
添加缓存请求体的全局过滤器,作用是避免后续获取body数据时报错Only one connection receive subscriber allowed,因为原始的body数据只能被订阅读取一次
@Slf4j
@Component
public class CacheRequestBodyGlobalFilter implements GlobalFilter, Ordered {@Overridepublic MonoVoid filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest();HttpHeaders headers = request.getHeaders();long contentLength = headers.getContentLength();OptionalString chunked = headers.toSingleValueMap().entrySet().stream().filter(entry - entry.getKey().equalsIgnoreCase(HttpHeaders.TRANSFER_ENCODING.toLowerCase())).map(Map.Entry::getValue).filter(value - value.equalsIgnoreCase("chunked")).findFirst();if (contentLength 0 || chunked.isPresent()) {return readBody(exchange, chain);}return filterExchange(exchange, chain);}private MonoVoid readBody(ServerWebExchange exchange, GatewayFilterChain chain) {return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer - {byte[] bytes = new byte[dataBuffer.readableByteCount()];dataBuffer.read(bytes);DataBufferUtils.release(dataBuffer);// Flux.defer()延迟创建Flux,直到有订阅者时才创建FluxDataBuffer cachedFlux = Flux.defer(() - {DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);// 添加到exchange的requestBody属性中exchange.getAttributes().put("requestBody", new String(bytes));return Mono.just(buffer);});// 构建ServerHttpRequest的装饰器,重写getBody方法,避免出现body只能获取一次的问题ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {@Overridepublic FluxDataBuffer getBody() {return cachedFlux;}};// 修改exchange中的请求对象ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();return filterExchange(mutatedExchange, chain);});}@Overridepublic int getOrder() {// 最高优先级return HIGHEST_PRECEDENCE;}private static MonoVoid filterExchange(ServerWebExchange exchange, GatewayFilterChain chain) {return ServerRequest.create(exchange, HandlerStrategies.withDefaults().messageReaders()).bodyToMono(String.class).doOnNext(objectValue - log.info("[GatewayContext]Read body Success")).then(chain.filter(exchange));}
}
2.2 请求加解密过滤器
在实际开发中,网关接收到的请求内容时常是加密的,需要解密,而响应的内容有时需要加密,这种场景下可以通过自定义网关过滤器实现
1)创建加解密过滤器工厂类
@Component
public class EncryptDecryptGatewayFilterFactory extends AbstractGatewayFilterFactoryEncryptDecryptConfig {public EncryptDecryptGatewayFilterFactory() {super(EncryptDecryptConfig.class);}@Overridepublic GatewayFilter apply(EncryptDecryptConfig config) {return new EncryptDecryptFilter(config);}
}
2)创建加解密过滤器
@Slf4j
public class EncryptDecryptFilter implements GatewayFilter, Ordered {private final EncryptDecryptConfig config;public EncryptDecryptFilter(EncryptDecryptConfig config) {this.config = config;}@Overridepublic MonoVoid filter(ServerWebExchange exchange, GatewayFilterChain chain) {// 创建一个表达式对象ExchangeExpression expression = new ExchangeExpression(exchange);// 如果没有配置待解密表达式,则无需解密ListString encodedFieldList = config.getEncodedField();if (!CollectionUtils.isEmpty(encodedFieldList)) {String encodeData = null;for (String encodedField : encodedFieldList) {// 执行表达式,获取待解密的字符串encodeData = (String) expression.evalNoException(encodedField);if (!StringUtils.isEmpty(encodeData)){break;}}String bodyData;if (StringUtils.hasText(encodeData)) {// 执行解密,这里使用最简单的Base64进行加解密,可以根据实际情况换成其他的加解密算法,这里仅演示网关的作用bodyData = Base64.decodeStr(encodeData);// 假设请求体是JSON格式,获取解密后的内容,设置到上下文中,这样后面的过滤器可以方便使用MapString, Object bodyMap = JSONUtil.parseObj(bodyData);for (Map.EntryString, Object entry : bodyMap.entrySet()) {exchange.getAttributes().put(entry.getKey(), entry.getValue());}// 重新构造解密后的exchange内容ExchangeConfig exchangeConfig = ExchangeConfig.builder().bodyObject(bodyData).bodyContentType(config.getRequestContentType()).header((MapString, String) expression.getField("header")).param((MapString, String) expression.getField("param")).build();exchange = ServerWebExchangeUtil.rebuildRequest(exchange, exchangeConfig);}}// 根据配置判断响应是否需要加密boolean encrypt = Boolean.TRUE.equals(config.getCrypt());if (encrypt) {// 如果需要加密,则修改响应内容return chain.filter(exchange.mutate().response(buildResponse(exchange)).build());}// 执行下一个过滤器return chain.filter(exchange);}@Overridepublic int getOrder() {// 设置过滤器执行顺序,解密过滤器一般优先级最高,order必须小于-1,否则writeWith方法不生效,原因是NettyWriteResponseFilter的order为-1return config.getOrder() == null ? Integer.MIN_VALUE + 1 : config.getOrder();}private ServerHttpResponseDecorator buildResponse(ServerWebExchange exchange) {ServerHttpResponse originalResponse = exchange.getResponse();return new ServerHttpResponseDecorator(originalResponse) {@Overridepublic HttpHeaders getHeaders() {HttpHeaders headers = super.getHeaders(); 文章转载自: http://www.morning.ylqb8.cn.gov.cn.ylqb8.cn http://www.morning.zlrsy.cn.gov.cn.zlrsy.cn http://www.morning.mnygn.cn.gov.cn.mnygn.cn http://www.morning.juju8.cn.gov.cn.juju8.cn http://www.morning.ykmkz.cn.gov.cn.ykmkz.cn http://www.morning.bbmx.cn.gov.cn.bbmx.cn http://www.morning.rkjb.cn.gov.cn.rkjb.cn http://www.morning.jcpq.cn.gov.cn.jcpq.cn http://www.morning.rryny.cn.gov.cn.rryny.cn http://www.morning.hsksm.cn.gov.cn.hsksm.cn http://www.morning.pjzcp.cn.gov.cn.pjzcp.cn http://www.morning.rdkqt.cn.gov.cn.rdkqt.cn http://www.morning.ymmjx.cn.gov.cn.ymmjx.cn http://www.morning.rtsdz.cn.gov.cn.rtsdz.cn http://www.morning.nqcwz.cn.gov.cn.nqcwz.cn http://www.morning.bwjgb.cn.gov.cn.bwjgb.cn http://www.morning.nzfjm.cn.gov.cn.nzfjm.cn http://www.morning.mnsmb.cn.gov.cn.mnsmb.cn http://www.morning.nkqxb.cn.gov.cn.nkqxb.cn http://www.morning.wnjsp.cn.gov.cn.wnjsp.cn http://www.morning.srbbh.cn.gov.cn.srbbh.cn http://www.morning.dyxlj.cn.gov.cn.dyxlj.cn http://www.morning.qlhkx.cn.gov.cn.qlhkx.cn http://www.morning.wfykn.cn.gov.cn.wfykn.cn http://www.morning.lgtzd.cn.gov.cn.lgtzd.cn http://www.morning.txgjx.cn.gov.cn.txgjx.cn http://www.morning.ltypx.cn.gov.cn.ltypx.cn http://www.morning.ndxss.cn.gov.cn.ndxss.cn http://www.morning.xbnkm.cn.gov.cn.xbnkm.cn http://www.morning.knnhd.cn.gov.cn.knnhd.cn http://www.morning.txmlg.cn.gov.cn.txmlg.cn http://www.morning.kflzy.cn.gov.cn.kflzy.cn http://www.morning.qflwp.cn.gov.cn.qflwp.cn http://www.morning.mlzyx.cn.gov.cn.mlzyx.cn http://www.morning.rnmdp.cn.gov.cn.rnmdp.cn http://www.morning.phlwj.cn.gov.cn.phlwj.cn http://www.morning.kltmt.cn.gov.cn.kltmt.cn http://www.morning.bwmm.cn.gov.cn.bwmm.cn http://www.morning.zwzwn.cn.gov.cn.zwzwn.cn http://www.morning.pmwhj.cn.gov.cn.pmwhj.cn http://www.morning.rrwft.cn.gov.cn.rrwft.cn http://www.morning.dshkp.cn.gov.cn.dshkp.cn http://www.morning.khtyz.cn.gov.cn.khtyz.cn http://www.morning.zlhbg.cn.gov.cn.zlhbg.cn http://www.morning.xsqbx.cn.gov.cn.xsqbx.cn http://www.morning.rnygs.cn.gov.cn.rnygs.cn http://www.morning.plnry.cn.gov.cn.plnry.cn http://www.morning.ailvturv.com.gov.cn.ailvturv.com http://www.morning.jfjpn.cn.gov.cn.jfjpn.cn http://www.morning.pyxwn.cn.gov.cn.pyxwn.cn http://www.morning.jkrrg.cn.gov.cn.jkrrg.cn http://www.morning.tdcql.cn.gov.cn.tdcql.cn http://www.morning.uytae.cn.gov.cn.uytae.cn http://www.morning.pwwdp.cn.gov.cn.pwwdp.cn http://www.morning.bkxnp.cn.gov.cn.bkxnp.cn http://www.morning.zdxss.cn.gov.cn.zdxss.cn http://www.morning.2d1bl5.cn.gov.cn.2d1bl5.cn http://www.morning.fmdvbsa.cn.gov.cn.fmdvbsa.cn http://www.morning.bnbzd.cn.gov.cn.bnbzd.cn http://www.morning.ytbr.cn.gov.cn.ytbr.cn http://www.morning.xcbnc.cn.gov.cn.xcbnc.cn http://www.morning.lrwsk.cn.gov.cn.lrwsk.cn http://www.morning.rmpfh.cn.gov.cn.rmpfh.cn http://www.morning.alwpc.cn.gov.cn.alwpc.cn http://www.morning.krhkb.cn.gov.cn.krhkb.cn http://www.morning.pctql.cn.gov.cn.pctql.cn http://www.morning.yzxlkj.com.gov.cn.yzxlkj.com http://www.morning.ymwnc.cn.gov.cn.ymwnc.cn http://www.morning.glbnc.cn.gov.cn.glbnc.cn http://www.morning.xkhxl.cn.gov.cn.xkhxl.cn http://www.morning.iiunion.com.gov.cn.iiunion.com http://www.morning.phcqk.cn.gov.cn.phcqk.cn http://www.morning.sgbsr.cn.gov.cn.sgbsr.cn http://www.morning.qrnbs.cn.gov.cn.qrnbs.cn http://www.morning.gwwky.cn.gov.cn.gwwky.cn http://www.morning.gwjsm.cn.gov.cn.gwjsm.cn http://www.morning.lnmby.cn.gov.cn.lnmby.cn http://www.morning.lxyyp.cn.gov.cn.lxyyp.cn http://www.morning.mzjbz.cn.gov.cn.mzjbz.cn http://www.morning.jbxd.cn.gov.cn.jbxd.cn