我曾经写过春季的休息服务,这些服务运行得非常好。
现在,我需要在向用户返回响应之前添加一些db事务。
此db事务与检索的响应无关。
例如,
@PostMapping("login")
public TransactionResponse loginAuthentication(@Valid @RequestBody LoginRequestBody loginRequest) {
TransactionResponse transactionResponse = new TransactionResponse();
try {
transactionResponse = loginService.validateUser(loginRequest);
//independent transaction needs to be executed in a separate thread
loginSerice.addLoginLog(transactionResponse);
//return below response without waiting to compelete above log transaction
return transactionResponse;
}
catch (Exception e) {
return CommonUtils.setErrorResponse(transactionResponse, e);
}
}我在spring 链接中读到了异步控制器。虽然控制器在单独的线程中执行各自的功能,但我不想等待db事务的完成。从服务层获得响应后,应该立即转发给用户。。
任何建议!!
春季版本为4.3
发布于 2018-10-01 20:14:15
我发布这个答案是为了帮助具有相同需求的开发人员(在一个单独的线程中执行一个空函数)。
由于我对多线程/异步环境没有经验,所以我希望通过使用spring异步方法来保持简单。
所以,首先我创建了线程池
@Configuration
@EnableAsync
public class ThreadConfig {
@Bean
public TaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(4);
executor.setMaxPoolSize(4);
executor.setThreadNamePrefix("WEBAPP");
executor.initialize();
return executor;
}
},然后我创建了一个服务,它将在一个单独的线程中执行我的代码.
@Async
@Service
@Transactional
public class LoggingService {
public void logintransaction() throws Exception{
System.out.println("start login loggin");
Thread.sleep(5000);
System.out.println("exit");
}
}最后,我在控制器上调用了上面的服务。我可以看到首先打印Total Time Taken,然后打印“开始登录日志”。这意味着我的新方法在一个新线程中执行。
@Autowired
private LoggingService loggingService;
@PostMapping("login")
public TransactionResponse loginAuthentication(@Valid @RequestBody LoginRequestBody loginRequest) {
long startTime = System.currentTimeMillis();
TransactionResponse transactionResponse = new TransactionResponse();
try {
transactionResponse = loginService.validateUser(loginRequest);
//independent transaction needs to be executed in a separate thread
//loginSerice.addLoginLog(transactionResponse);
loggingService.logintransaction();
//return below response without waiting to compelete above log transaction
System.err.println("Total Time Taken=>"+(System.currentTimeMillis() - startTime));
return transactionResponse;
}
catch (Exception e) {
return CommonUtils.setErrorResponse(transactionResponse, e);
}
}谢谢
https://stackoverflow.com/questions/52572717
复制相似问题