spring管理不了thread中的事务。
java主类由spring管理,主类中调用thread,目标是:thread中逻辑有异常后,所有事务回滚。
下面是thread的实现,必须开启一个新的事务,单独管理线程中的逻辑
class BusiOrderSaveThread extends Thread{
BusiOrder busiOrder;
LoginOpr loginOpr;
CountDownLatch countdown ;
IBusiPubOrder busiPubOrder;
private Map<String,String> map;
private boolean flag;
/**
* @param bo
* @param loginOpr
* @throws IOException
* @throws IOException
*/
public BusiOrderSaveThread(BusiOrder busiOrder, LoginOpr loginOpr,CountDownLatch countdown,IBusiPubOrder busiPubOrder,Map<String,String> map,boolean flag) throws IOException {
super();
this.busiOrder=busiOrder;
this.loginOpr = loginOpr;
this.countdown = countdown;
this.busiPubOrder = busiPubOrder;
this.map = map;
this.flag = flag;
}
@SuppressWarnings("unchecked")
@Override
public void run() {
long id = Thread.currentThread().getId();
DataSourceTransactionManager transactionManager =
(DataSourceTransactionManager) SpringContextFactory.getBean("transactionManager");
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); //事物隔离级别
TransactionStatus status = transactionManager.getTransaction(def); //获得事务状态
try {
if(flag){
this.busiPubOrder.saveOrder(this.busiOrder, this.loginOpr);
String a =null;
if(a.equals("1"));
}
transactionManager.commit(status);
} catch (Exception e) {
flag =false;
if(e instanceof BusiException){
BusiException ex = (BusiException)e;
this.map.put("false"+id,ex.getErrMsg());
}else{
this.map.put("false"+id,e.getMessage());
}
transactionManager.rollback(status);
}finally{
this.countdown.countDown();
}
}
}
主类调用:
//深度拷贝
BusiOrder bo = new BusiOrder();
bo=(BusiOrder)JavaTool.cloneObject(busiOrder);
ThreadExcutorSingleton.service.execute(new BusiOrderSaveThread(bo,loginOpr,countdown,busiPubOrder,map,flag));
}
countdown.await();
//获取异常信息 begin add by zhaozj
Set<String> keys = map.keySet();
List<String> errorList = new ArrayList<String>();
if(keys!=null&&keys.size()>0){
for(String key:keys){
errorList.add(map.get(key));
}
throw new BusiException("成员管理保存订单异常:"+errorList.get(0));
}