優雅的使用 ThreadLocalide
維持線程封閉性的一種更規範的方法就是使用 ThreadLocal,這個類能使線程中的某個值與保存的值的對象關聯起來。ThreadLocal提供 get和 set等接口或方法,這些方法爲每個使用這個變量的線程都存有一份獨立的副本,所以 get老是返回由當前線程在調用 set時設置的最新值。ThreadLocal有以下方法 post
一、get()方法是用來獲取ThreadLocal在當前線程中保存的變量副本this
二、set()用來設置當前線程中變量的副本線程
三、remove()用來移除當前線程中變量的副本對象
四、initialValue()是一個protected方法,通常是用來在使用時進行重寫的,若是在沒有set的時候就調用 get,會調用 initialValue方法初始化內容。爲了使用的更放心,咱們簡單的接口
首先準備一個BaseSigntureRequest類用來存放公共參數rem
- public class BaseSignatureRequest {
- private String device;
-
- public String getDevice() {
- return device;
- }
-
- public void setDevice(String device) {
- this.device = device;
- }
- }
-
複製代碼get
- public class ThreadLocalCache {
- public static ThreadLocal<BaseSignatureRequest>
- baseSignatureRequestThreadLocal = new ThreadLocal<>();
- }
-
複製代碼it
而後編寫一個 Interceptor,在請求的時候獲取 device參數,存入當前線程的 ThreadLocal中。這裏須要注意的是,重寫了 afterCompletion方法,當請求結束的時候把 ThreadLocalremove,移除沒必要需要鍵值對。io
- public class ParameterInterceptor implements HandlerInterceptor {
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
- Object handler) throws Exception {
- String device = request.getParameter("device");
- BaseSignatureRequest baseSignatureRequest = new BaseSignatureRequest();
- baseSignatureRequest.setDevice(device);
- ThreadLocalCache.baseSignatureRequestThreadLocal.set(baseSignatureRequest);
- return true;
- }
-
- @Override
- public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
- Object handler, Exception ex) throws Exception {
- ThreadLocalCache.baseSignatureRequestThreadLocal.remove();
- }
- @Override
- public void postHandle(HttpServletRequest httpServletRequest,
- HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
-
- }
- }