多线程中,ServletUtils获取request对象为空

1.问题描述:
在使用ServletUtils工具类中的静态方法获取request对象时,在controller层可以获取到,在service实现类中无法获取。

LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

2.原因分析:
controller层开启了多线程。(开启多线程之前可以获取到,开启之后在子线程中无法获取)原因是request 信息是存储在 ThreadLocal 中的,所以子线程根本无法获取到主线程的 request 信息。

//创建线程对象
private void createThead(String key) throws Exception {
    Thread thread = new Thread(new getKey(key));
    thread.start();
}

//开启线程
private class getKey implements Runnable{
   private Key key;
   public getKey(Key key) {
       this.key = key;
   }
   //Runnable接口中的抽象方法
   public void run() {
       try {
           getKey(key);
       } catch (Exception e) {
           System.out.println(e);
       }
   }
}

3.解决方法:
在新开子线程之前增加两行代码,将RequestAttributes对象设置为子线程共享。

//创建线程对象
private void createThead(String key) throws Exception {
	//将RequestAttributes对象设置为子线程共享
	ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
	RequestContextHolder.setRequestAttributes(sra, true);
    Thread thread = new Thread(new getKey(key));
    thread.start();
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值