日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

ThreadLocal使用,配合攔截器HandlerInterceptor使用

作者:Bunny0212 更新時間: 2024-03-14 編程語言

ThreadLocal使用,配合攔截器HandlerInterceptor使用

ThreadLocal的使用場景通常涉及多線程環境下需要為每個線程保留獨立狀態的情況。它提供了一種簡單的方式來管理線程本地變量,使得每個線程都可以獨立地訪問和修改自己的變量副本,而不會影響其他線程的副本。

包括的方法

ThreadLocal的主要方法包括:

  • get():獲取當前線程的變量副本。
  • set(value):設置當前線程的變量副本為給定的值。
  • remove():移除當前線程的變量副本。

項目中創建

定義BaseContext類,分別設置獲取當前內容、設置當前內容、移出當前內容。

public class BaseContext {
    public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    public static Long getCurrentId() {
        return threadLocal.get();
    }

    public static void setCurrentId(Long currentId) {
        threadLocal.set(currentId);
    }

    public static void removeCurrentId(Long id) {
        threadLocal.remove();
    }
}

需要注意的是,ThreadLocal使用完畢后應該及時調用remove()方法來清除當前線程的變量副本,以避免內存泄漏問題。另外,由于ThreadLocal使用了線程封閉的設計思想,因此在使用時應當謹慎考慮其適用性,并避免濫用。

在項目中簡單使用

在發送請求時,攜帶id,最后在service層獲取。

@RestController
@RequestMapping("/test")
@Tag(name = "測試設置ThreadLocal")
@Slf4j
public class DemoThreadLocal {
    @Autowired
    DemoThreadLocalService demoThreadLocalService;

    @Operation(summary = "設置userID", description = "測試方法")
    @GetMapping("userId={id}")
    public String setUserId(@PathVariable Long id) {
        BaseContext.setCurrentId(id);
        demoThreadLocalService.demoThreadLocalUserId();
        return "userId";
    }
}

service接口。

public interface DemoThreadLocalService {
    void demoThreadLocalUserId();
}

service實現類中獲取id。

@Service
@Slf4j
public class DemoThreadLocalServiceImpl implements DemoThreadLocalService {
    @Override
    public void demoThreadLocalUserId() {
        // 獲取當前id
        Long currentId = BaseContext.getCurrentId();
        log.info("當前id為:{}", currentId);
        // 使用完后移出
        BaseContext.removeCurrentId(currentId);
    }
}

在這里插入圖片描述

配合攔截器使用

第一步:配置攔截器

  1. 新建interceptor包和TokenUserInterceptor類,實現HandlerInterceptor;并交給spring管理。

  2. 實現public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception方法。

  3. 我是將token放在header中的,當然也可以放在cookies中。

    • 在這里插入圖片描述
  4. 判斷當前token是否為空,如果為空返回false,不往下執行。

  5. 做到這步還沒結束,因為這樣寫還不會生效。

  6. 新建config包,創建WebMvcConfiguration 并實現WebMvcConfigurationSupport

@Component
@Slf4j
public class TokenUserInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 設置userId
        String token = request.getHeader("token");
        System.out.println("--------------" + token + "--------------");
        if (token != null && !token.isEmpty()) {
            BaseContext.setCurrentId(Long.valueOf(token));
            return true;
        } else {
            return false;
        }
    }
}

第二步:配置MVC設置

匹配路徑

WebMvcConfiguration內容如下。配置攔截器這樣才會生效。需要攔截/test下所有請求,如圖所示,攔截器識別不了通配符所以要使用addPathPatterns去匹配。

其中的方式是:protected void addInterceptors(InterceptorRegistry registry)

@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    @Autowired
    TokenUserInterceptor tokenUserInterceptor;

    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenUserInterceptor).addPathPatterns("/test/**");
    }
}

在這里插入圖片描述

需要注意的是,當前只是傳入一個也可以傳入多個。當匹配后即可實現攔截效果,檢測header中是否包含token。

在這里插入圖片描述

示例,為了演示效果就隨便寫了下。

protected void addInterceptors(InterceptorRegistry registry) {
    String[] list = {};
    registry.addInterceptor(tokenUserInterceptor)
            .addPathPatterns("/test/**").addPathPatterns("/test2").addPathPatterns("/test3")
            .addPathPatterns("asa", "sas","sas")
            .addPathPatterns(list);
}

在knif4j中測試,成功輸出。

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

排出路徑

排出哪些路徑是不需要攔截的。

protected void addInterceptors(InterceptorRegistry registry) {
    String[] list = {};
    registry.addInterceptor(tokenUserInterceptor)
            .addPathPatterns("/test/**").excludePathPatterns("/test2").excludePathPatterns("/test3")
            .excludePathPatterns("asa", "sas", "sas")
            .excludePathPatterns(list);
}

在這里插入圖片描述

第三步:Controller層中

controller層,在路徑中不傳入id,通過攔截器獲取header中token。這一層并不需要做什么,只是為了寫一個接口讓MVC攔截。

@RestController
@RequestMapping("/test")
@Tag(name = "測試設置ThreadLocal")
@Slf4j
public class DemoThreadLocal {
    @Autowired
    DemoThreadLocalService demoThreadLocalService;

    @Operation(summary = "攔截器中設置UserId", description = "測試方法")
    @GetMapping("userId")
    public String userId() {
        demoThreadLocalService.demoThreadLocalUserId();
        return "userId";
    }
}

第四步:查看內容

service和上面一樣。

@Service
@Slf4j
public class DemoThreadLocalServiceImpl implements DemoThreadLocalService {
    @Override
    public void demoThreadLocalUserId() {
        // 獲取當前id
        Long currentId = BaseContext.getCurrentId();
        log.info("當前id為:{}", currentId);
        // 使用完后移出
        BaseContext.removeCurrentId(currentId);
    }
}
emoThreadLocalUserId() {
        // 獲取當前id
        Long currentId = BaseContext.getCurrentId();
        log.info("當前id為:{}", currentId);
        // 使用完后移出
        BaseContext.removeCurrentId(currentId);
    }
}

原文鏈接:https://blog.csdn.net/weixin_46533577/article/details/136608293

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新