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

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

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

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

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

ThreadLocal的使用場(chǎng)景通常涉及多線程環(huán)境下需要為每個(gè)線程保留獨(dú)立狀態(tài)的情況。它提供了一種簡(jiǎn)單的方式來管理線程本地變量,使得每個(gè)線程都可以獨(dú)立地訪問和修改自己的變量副本,而不會(huì)影響其他線程的副本。

包括的方法

ThreadLocal的主要方法包括:

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

項(xiàng)目中創(chuàng)建

定義BaseContext類,分別設(shè)置獲取當(dāng)前內(nèi)容、設(shè)置當(dāng)前內(nèi)容、移出當(dāng)前內(nèi)容。

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使用完畢后應(yīng)該及時(shí)調(diào)用remove()方法來清除當(dāng)前線程的變量副本,以避免內(nèi)存泄漏問題。另外,由于ThreadLocal使用了線程封閉的設(shè)計(jì)思想,因此在使用時(shí)應(yīng)當(dāng)謹(jǐn)慎考慮其適用性,并避免濫用。

在項(xiàng)目中簡(jiǎn)單使用

在發(fā)送請(qǐng)求時(shí),攜帶id,最后在service層獲取。

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

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

service接口。

public interface DemoThreadLocalService {
    void demoThreadLocalUserId();
}

service實(shí)現(xiàn)類中獲取id。

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

在這里插入圖片描述

配合攔截器使用

第一步:配置攔截器

  1. 新建interceptor包和TokenUserInterceptor類,實(shí)現(xiàn)HandlerInterceptor;并交給spring管理。

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

  3. 我是將token放在header中的,當(dāng)然也可以放在cookies中。

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

  5. 做到這步還沒結(jié)束,因?yàn)檫@樣寫還不會(huì)生效。

  6. 新建config包,創(chuàng)建WebMvcConfiguration 并實(shí)現(xiàn)WebMvcConfigurationSupport

@Component
@Slf4j
public class TokenUserInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 設(shè)置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設(shè)置

匹配路徑

WebMvcConfiguration內(nèi)容如下。配置攔截器這樣才會(huì)生效。需要攔截/test下所有請(qǐng)求,如圖所示,攔截器識(shí)別不了通配符所以要使用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/**");
    }
}

在這里插入圖片描述

需要注意的是,當(dāng)前只是傳入一個(gè)也可以傳入多個(gè)。當(dāng)匹配后即可實(shí)現(xiàn)攔截效果,檢測(cè)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中測(cè)試,成功輸出。

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

排出路徑

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

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。這一層并不需要做什么,只是為了寫一個(gè)接口讓MVC攔截。

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

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

第四步:查看內(nèi)容

service和上面一樣。

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

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

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