定义Threadlocal工具类使用拦截器统一释放资源

2023-12-25 11:55:51

一、ThreadLocalUtil 工具类定义

import java.util.HashMap;
import java.util.Map;

public class ThreadLocalUtil {

    private static final ThreadLocal<Map<String, Object>> threadLocal = ThreadLocal.withInitial(() -> new HashMap<>(10));

    public static Map<String, Object> getThreadLocal() {
        return threadLocal.get();
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        return map.get(key);
    }

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        map.put(key, value);
    }

    public static void set(Map<String, Object> keyValueMap) {
        Map<String, Object> map = threadLocal.get();
        map.putAll(keyValueMap);
    }

    public static void remove() {
        threadLocal.remove();
    }

    public static <T> T remove(String key) {
        Map<String, Object> map = threadLocal.get();
        return (T) map.remove(key);
    }

}

二、定义拦截器释放资源

释放资源常见的我们可以定义一个拦截器,在afterCompletion方法(方法执行完成,页面渲染以后执行,或者方法执行失败执行)中去释放资源,避免内存溢出

定义拦截器:

@Component
public class xxxInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove(); 
    }
}

把拦截器放到容器中:

@Configuration
public class AdminWebConfig implements WebMvcConfigurer {
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new xxxInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**"); //放行的请求
    }
}

备注:

withInitial方法是ThreadLocal类的一个静态方法,

用于创建一个带有初始值的ThreadLocal对象(SuppliedThreadLocal)。

参数是一个Supplier接口,Supplier的生产者意思,接受一个Lambda的函数。返回一个值

public static <S> ThreadLocal<S> withInitial(Supplier<? extends S> supplier) {
    return new SuppliedThreadLocal<>(supplier);
}

使用WebMvcConfigurationSupport有误导致自定义的WebMvcConfigurer失效

文章来源:https://blog.csdn.net/QJY1437758743/article/details/135194024
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。