我的业务层是在glassfish3上实现的,其中有webservices ontop stack stack。
为了轻松处理交易,我们使用逻辑处理程序,每次发出,关闭或出现单个请求时都会调用它。
在close和fault方法中,我们检查是否有任何事务处于打开状态并回滚它们。
这样做我们使用threadlocal,但当然只有在逻辑处理程序在具体的Web服务类的同一个线程中运行时才有效。
public class WebServiceMessageHandler implements LogicalHandler<LogicalMessageContext>
@Override
public void close(MessageContext context)
{
DataLayerTransactionManager.RollBackTransactions();
}
@Override
public boolean handleFault(LogicalMessageContext context)
{
DataLayerTransactionManager.RollBackTransactions();
return true;
}
public class DataLayerTransactionManager
{
static ThreadLocal> threadLocalDAOList = new ThreadLocal>();
public static void Add(DataLayerSession dao)
{
List list;
list=threadLocalDAOList.get();
if ( list == null )
{
list=new ArrayList();
threadLocalDAOList.set(list);
}
list.add(dao);
}
public static void Remove(DataLayerSession dao)
{
List list;
list=threadLocalDAOList.get();
if ( list == null )
return;
list.remove(dao);
}
public static void RollBackTransactions()
{
List list;
list=DataLayerTransactionManager.threadLocalDAOList.get();
if ( DataLayerTransactionManager.threadLocalDAOList.get()==null)
return;
for (DataLayerSession session : list)
{
try
{
session.rollbackTransaction();
Logger log;
log=LoggerFactory.getLogger(DataLayerTransactionManager.class);
log.error("Rollingback pending transaction "+session.toString() );
}
catch (Exception e)
{
Logger log;
log=LoggerFactory.getLogger(DataLayerTransactionManager.class);
log.error("",e);
}
}
list.clear();
DataLayerTransactionManager.threadLocalDAOList.set(null);
}
}