webflux - 统一响应 ModifyResponseBodyGatewayFilterFactory

webflux提供了对响应结果的修改的过滤器 ModifyResponseBodyGatewayFilterFactory, 如果需要返回自定义格式,只需要重写指定 ModifyResponseBodyGatewayFilterFactory.Config中的 rewriteFunction

ModifyResponseBodyGatewayFilterFactory.Config:

public static class Config {

		private Class inClass;

		private Class outClass;

		private Map<String, Object> inHints;

		private Map<String, Object> outHints;

		private String newContentType;
    	//重写指定
		private RewriteFunction rewriteFunction;
}

实例

BodyRewriteFunction

@Slf4j
public class BodyRewriteFunction implements RewriteFunction<byte[], byte[]> {

    @Override
    public Publisher<byte[]> apply(ServerWebExchange exchange, byte[] bytes) {

        ServerHttpResponse response = exchange.getResponse();
        if (!ServerWebExchangeUtils.isAlreadyRouted(exchange)){
            //请求

        }else {
            //响应
         	Result<Object> result = Result.ok()
            return Mono.just(JSONUtil.toJsonStr(result).getBytes());
        }

        return Mono.just(bytes);
    }
}

ResponseBodyFilter :

public class ResponseBodyFilter implements GlobalFilter, Ordered {


    private GatewayFilter delegate;

    public ResponseBodyFilter(ModifyResponseBodyGatewayFilterFactory modifyResponseBodyGatewayFilterFactory, 
    					BodyRewriteFunction rewriteFunction) {
		        delegate = modifyResponseBodyGatewayFilterFactory
		        .apply(new ModifyResponseBodyGatewayFilterFactory.Config()
		                .setRewriteFunction(rewriteFunction)
		                .setInClass(byte[].class)
		                .setOutClass(byte[].class));
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return delegate.filter(exchange, chain);
    }

    @Override
    public int getOrder() {
        return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
    }
}

配置过滤器文件 FrameConfig :

@Configuration
public class FrameConfig {

    @Bean
    public BodyRewriteFunction bodyRewriteFunction() {
        return new BodyRewriteFunction();
    }

    @Bean
    public ResponseBodyFilter responseBodyFilter(ModifyResponseBodyGatewayFilterFactory filterFactory) {
        return new ResponseBodyFilter(filterFactory, bodyRewriteFunction());
    }
}

响应结果:

{
    'code': 200,
    'data':{
        //omit...
    }
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐