threadLocal的使用

本文介绍了一种利用ThreadLocal实现跨层传递request和response的方法。通过定义ThreadLocalContext类及其get、set和remove方法,可以在service层便捷地获取到request信息,有效避免了参数重复传递的问题,并强调了使用完毕后及时清理资源的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值