Filter
基本使用
@Bean
public Filter addHeaderFilter() {
return new Filter() {
@Override
public CompletableFuture<Void> doFilter(AsyncRequest request, AsyncResponse response, FilterChain chain) {
request.setHeader("foo", "bar");
return chain.doFilter(request, response);
}
};
}
上面的例子将会给所有到来的请求都加上一个固定的Header。
异步Filter
@Bean
public Filter filter() {
return new Filter() {
@Override
public CompletableFuture<Void> doFilter(AsyncRequest request, AsyncResponse response, FilterChain chain) {
return CompletableFuture.runAsync(() -> {
// do something...
}).thenCompose(r -> {
// invoke next filter
return chain.doFilter(request, response);
});
}
};
}
上面的例子演示了在doFilter(xxx)
中进行异步操作,并在该操作完成后回调FilterChain
继续执行后续操作。
Tip
上面演示的异步只是开了一个新的线程, 实际场景中可使用Netty
等实现更优雅的异步方式。
终止Filter
的执行
当不期望执行后续的Filter
时可返回一个CompletableFuture.completedFuture(null)
实例。
@Override
public CompletableFuture<Void> doFilter(AsyncRequest request, AsyncResponse response, FilterChain chain) {
return CompletableFuture.completedFuture(null);
}
Warning
doFilter(xxx)
请勿返回null
- 所有方法都将会在IO线程上调用,尽量不要阻塞, 否则将对性能会有较大的影响。
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.
Last modified July 28, 2022: refactor main docs to v0.1.1 (#199) (8423db1)