应该实现和使用哪个HandlerInterceptorAdapter方法来清除ThreadLocal?

huangapple go评论29阅读模式
英文:

Which HandlerInterceptorAdapter method should be implemented and used to clear ThreadLocal?

问题

我已经编写了HandlerInterceptorAdapter的实现。它将一些与请求相关的数据放入了ThreadLocal中。因为线程会被重用来处理新的请求,所以在处理请求时必须将放入ThreadLocal的数据清除掉。我应该实现哪个HandlerInterceptorAdapter方法来清除它呢?我看到有两个选项,一个是postHandle,另一个是afterCompletion。我需要确保ThreadLocal中的数据被移除。

英文:

I have written an implementation of HandlerInterceptorAdapter. It is putting some request specific data in a ThreadLocal. Because threads are reused for new requests the data that was put in the ThreadLocal has to be removed when request is handled. Which HandlerInterceptorAdapter method should I implement to clear it? There are two options as I see it, postHandle and afterCompletion. I need that data in the ThreadLocal is guaranteed to be removed.

答案1

得分: 2

使用afterCompletion。它将在任何结果上被调用
> 在请求处理完成后,即在渲染视图后,回调函数将被调用。它将在处理程序执行的任何结果上被调用,因此允许进行适当的资源清理

参考

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html

注意

  • 如果你打算从preHandle中返回false,那么你应该在preHandle中清理线程本地存储,因为false表示你已经处理了响应,因此不会调用postHanlde()afterCompletion
英文:

Use the afterCompletion. It will be called on any outcome
> Callback after completion of request processing, that is, after rendering the view. Will be called on any outcome of handler execution, thus allows for proper resource cleanup.

Reference

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html

Note

  • If you are going to return false from from preHandle you should clean up thread local in the pre handle itself because false means you have handled the response, as a result postHanlde() or afterCompletion will not be called

huangapple
  • 本文由 发表于 2020年8月2日 01:32:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63208163.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定