简单异步编程实现
spring最快捷简单的异步编程就是直接添加注解@Async,例:
@Service
public class MyCommonTestServiceImpl implements MyCommonTestService {
@Async
@Override
public void testAsync() {
System.out.println("*****************业务实现*********************");
}
}
但如果在复杂的项目业务中,新建线程可能需要使用主线程的上下文信息,例如Request里的认证信息token。假如token存放在request的header里,获取方式:
RequestAttributes context = RequestContextHolder.currentRequestAttributes();
ServletRequestAttributes attributes = (ServletRequestAttributes) context;
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("token");
那么上述的简单实现就满足不了因为新建的线程里没有这个上下文信息。
此时可采用自定义线程池实现
自定义线程池
1、实现TaskDecorator自定义线程创建
import com.rongwei.rwcommonconfig.config.ThreadLocalResource;
import org.springframework.core.task.TaskDecorator;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes