SpringBoot异步请求时获取ServletRequestAttributes为空,request空指针问题

项目使用@Async注解进行异步请求,获取RequestAttributes为空,后续操作中从request获取参数报错,后查询资料解决;

 方法一:异步之前开启子线程共享

设置值:

ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 
sra.setAttribute("key","value",1);//设置参数值
RequestContextHolder.setRequestAttributes(sra, true);//设置子线程共享

取值: 

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if(attributes != null) {
   String value = attributes.getAttribute("key", 1);
}

 结果:本地idea测试通过,部署到服务器后失效,原因未深究,使用了方法二。

 方法二:使用 ThreadLocal传递参数

Threadlocal是一个线程内部的存储类,可以在指定线程内存储数据,数据存储以后,只有指定线程可以得到存储数据

 设置值:异步方法传入参数,将参数设置到ThreadLocalUtil中 

@Async
public void testAsyn(String name) {
    ThreadLocalUtil.set("name", name);
    // .......
}

 取值:在异步方法中获取参数

String ThreadLocalUtil.get("name");

结果:解决问题

附带ThreadLocalUtil工具类代码:https://blog.csdn.net/weixin_42260124/article/details/118763029

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot中进行异步请求可以使用Spring的异步支持。以下是一种常见的实现方式: 1. 首先,在Spring Boot应用程序的配置类或主类上添加`@EnableAsync`注解,以启用异步支持。 ```java import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @EnableAsync @SpringBootApplication public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } ``` 2. 在需要进行异步请求的方法上添加`@Async`注解,表明该方法是一个异步方法。 ```java import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @Service public class YourService { @Async public void doAsyncOperation() { // 异步执行的逻辑 } } ``` 3. 在需要调用异步方法的地方,通过依赖注入的方式获取到异步方法所在的类的实例,并调用相应的异步方法。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class YourController { @Autowired private YourService yourService; @GetMapping("/async") public String asyncRequest() { yourService.doAsyncOperation(); return "Async request submitted"; } } ``` 以上代码示例中,`YourService`类中的`doAsyncOperation`方法是一个异步方法,在`YourController`类中的`asyncRequest`方法中调用了该异步方法。在调用异步方法后,控制权会立即返回给调用方,而异步方法会在后台线程中执行。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值