threadLocal的使用

threadLocal的概念这里不做表述,主要说下如何使用

例如: 我们在service层需要用到request,除了注入/传参数的形式外,还可以使用threadLocal,当然,threadLocal还可以用在其他情况,非常方便

首先定义要使用的类

public class ThreadLocalContext {
    private static ThreadLocal<HttpServletRequest> threadRequest = new ThreadLocal<HttpServletRequest>();  
    private static ThreadLocal<HttpServletResponse> threadResponse = new ThreadLocal<HttpServletResponse>();  
    public static void setRequest(HttpServletRequest request) {  
        threadRequest.set(request);  
    }  
    public static HttpServletRequest getRequest() {  
        HttpServletRequest request = threadRequest.get();  
        return request;  
    }  
    public static void removeRequest() {  
        threadRequest.remove();  
    }  
      
    public static void setResponse(HttpServletResponse response) {  
        threadResponse.set(response);  
    }  
  
    public static HttpServletResponse getResponse() {  
        HttpServletResponse response = threadResponse.get();  
        return response;  
    }  
  
    public static void removeResponse() {  
        threadResponse.remove();  
    }  
}

里面变量写成静态,这里是使用request的,如上,主要包括get/set/remove方法,这里要记住每次使用完之后,要remove掉,不然容易产生内存泄露问题,使用try-catch的方式:

try{

//do something
    ThreadLocalContext.setRequest(request);
    ThreadLocalContext.setResponse(response);
}catch(Exception e){
            e.printStackTrace();
        }finally{
            ThreadLocalContext.removeRequest();
            ThreadLocalContext.removeResponse();
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值