我有一个要求,我在 GUI 上进行一些操作,一旦我将数据保存在 DB 中,我需要向 web 服务发送一个 http 请求。但是对 GUI 的响应不应等待 web 服务请求的结果。为此,我使用 @Async ,即 Spring 的注释。这是我的结构
MyConroller.java
调用方法
goSaveAndCreate
(非异步)在
ServiceA.java
ServiceA中注入了一个ServiceB bean。一个方法 ,
@Async
create()
在ServiceB中使用 Async 进行注释。现在 ServiceA.goSaveAndCreate 自己调用一个方法,保存并调用 ServiceB.create() (这是异步的)。我可以在日志中看到创建了一个正在执行 create 方法的新线程。但是在某个特定点停止后突然记录日志,并且该线程似乎已被杀死或完成。
@Service("MarginCalculationService")
public class ServiceA implements ServiceAI {
private static final String APPROVED = "APPROVED";
public static final String SUCCESS = "SUCCESS";
....
@Autowired
ServiceB serviceB;
public List<VV> goSaveAndCreate(String[] ids,List<XX> calList) throws Exception, DataAccessException {
try {
Pair<List<VG>,List<UU>> resultList = save(ids);
vvList = resultList.getFirst();
/*
* HKAPIL - Send Message to webService callingserviceB
*/
if(resultList.getSecond() != null){
serviceB.create(resultList.getSecond());
}
} catch (DataAccessException e) {
e.printStackTrace();
logger.error("Data Access Exception thrown during - " , e);
throw e;
} catch (Exception e){
e.printStackTrace();
logger.error("Exception thrown during " , e);
throw e;
}
System.out.println("Exiting the method in MCSERVICE");
return vvList;
}
private save(){
...
...
}
}
二次服务
@Service("wireInstructionMessageService")
public class ServiceB implements ServiceBI {
@Async
@Override
public void create(List<Ralc> calcList) {
String threadName = Thread.currentThread().getName();
logger.info("Inside a different thread [" + threadName + " ] to send message ." );
..
...
otherMethod(Obj);
}
private otherMethod(Obj obj){
...
...
..
//tills this point logs are getting printed nothing after this
..
...
}
}
applciationContext.xml 条目
<!-- Defines a ThreadPoolTaskExecutor instance with configurable pool size, queue-capacity, keep-alive,
and rejection-policy values. The id becomes the default thread name prefix -->
<task:executor id="MyMessageExecutor"
pool-size="5-25"
queue-capacity="100"/>
<task:annotation-driven executor="MyMessageExecutor"/>
现在我有两个问题
1)有没有一种方法可以在某些方法中添加一些日志,告诉我来自 MyExecutor 的新线程正在被杀死或 MyExecutor 正在关闭(我们在普通 Java ExecutorService 中的方式)2)我是否以错误的方式使用 Asyn ? 是否有可能一旦方法从 Controller 或 ServiceA 返回, ServiceB 实例也会被清理?
感谢 HKapil