java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java子线程获取主线程的request对象

java子线程解决获取主线程的request对象问题

作者:weixin_45644548

这篇文章主要介绍了java子线程解决获取主线程的request对象问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

java子线程获取主线程的request对象

问题描述

业务系统,多线程处理业务是提供性能方法之一,在使用中,我们会将某些数据存储在request中,传给后面的组件使用,不需要在方法中定义变量来传递,提高代码的美观可读性,

我们使用request.setAttribute(“xxxx”, “xxxx”)方式传递参数,后面的组件或方法使用如下代码获取参数:

ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
Object param = request.getAttribute(“xxxx”);

在主线程下这么写是没问题的,但是子线程下request 对象是空的,子线程不共享主线程的request对象

解决办法

在启动线程前,执行以下代码即可,子线程也可以共享主线程的request对象

ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
RequestContextHolder.setRequestAttributes(sra, true);

示例

多线程子线程获取不到主线程的request

使用多线程时有时候会碰到子线程获取不到主线程的request

原因是子线程还未执行完成而主线程已经执行完毕则导致子线程获取不到

我们只需要加上两句代码即可

// RequestAttributes对象设置为子线程共享
// 解决开启多线程时子线程获取不到主线程的request
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
RequestContextHolder.setRequestAttributes(attributes, true);

我还遇到一个问题则是即时按照上面设置共享,但是获取不到主线程的header,目前使用了一个笨方法则是把主线程的header需要使用的参数在主线程内拿出来定义一个变量提供给子线程使用。。。

mysql触发器语法注意事项

注意点:

1. 在if条件里的必须是变量(@xxx)

2. set分号结尾

3. end if注意分号结尾

4. 条件中执行的sql语句注意分号结尾例子:Navicat 创建触发器

BEGIN
set @dataTime = date(new.dataTime);
set @nowTime = date(now());
set @yearDT = year(new.dataTime);
set @monthDT = month(new.dataTime);
set @yearN = year(now());
set @monthN = month(now());
if @dataTime = @nowTime then
insert into t_senor_data_day values(new.id,new.deviceId,new.senorId,new.tenantId,new.dataValue,new.dataTime,new.receiveTime,new.taskType,new.paramType,new.senorType);
end if;
if @yearDT = @yearN and @monthDT = @monthN then
insert into t_senor_data_month values(new.id,new.deviceId,new.senorId,new.tenantId,new.dataValue,new.dataTime,new.receiveTime,new.taskType,new.paramType,new.senorType);
end if;
end

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文