Spring线程事务问题

AN安分分 发布于 2016/08/30 16:42
阅读 467
收藏 0

问题描述:

    进行操作时给申请单货物明细生成序列号(必须唯一),然后改变申请单状态;

解决办法:

    采用线程同步解决多用户操作生成序列号唯一,线程由spring来控制但是随之带来新问题,线程事务独立,执行异常不回滚;

代码片段:

public class RequestNoteController extends BaseController {


		public @ResponseBody String submitOper(String[] ids) {
			...
			new StartTaskThread(threadPoolTaskExecutor,requestNoteItemService,requestNoteItem,getShiroUser()).run();//生成序列号
			...
			service.batchSubmit(ids, getShiroUser());//改变状态,如果改变状态失败,生成序列号的方法不会回滚
}
public class StartTaskThread implements Runnable {

	private ThreadPoolTaskExecutor threadPoolTaskExecutor;
	private RequestNoteItemService requestNoteItemService;
	RequestNoteItem requestNoteItem;
	ShiroUser shiroUser;

	public StartTaskThread(ThreadPoolTaskExecutor threadPoolTaskExecutor, RequestNoteItemService requestNoteItemService,RequestNoteItem requestNoteItem,ShiroUser shiroUser) {
		this.threadPoolTaskExecutor = threadPoolTaskExecutor;
		this.shiroUser = shiroUser;
		this.requestNoteItem = requestNoteItem;
		this.requestNoteItemService = requestNoteItemService;
	}


	@Override
	public void run() {
		String result = null;
		FutureTask<String> futureTask = new FutureTask<String>(new CallableThread(requestNoteItem,shiroUser,requestNoteItemService));
		threadPoolTaskExecutor.execute(futureTask);
		try {
			// 取得结果,同时设置超时执行时间为1秒。同样可以用future.get(),不设置执行超时时间取得结果
			result = futureTask.get();
		} catch (InterruptedException e) {
			futureTask.cancel(true);
		} catch (ExecutionException e) {
			futureTask.cancel(true);
		} catch (Exception e) {
			futureTask.cancel(true);
			// 超时后,进行相应处理
		}finally {
			System.out.println(result);
		}
	}
}    

public class CallableThread implements Callable<String> {

	private RequestNoteItemService requestNoteItemService;
	RequestNoteItem requestNoteItem;
	ShiroUser shiroUser;

	public CallableThread(RequestNoteItem requestNoteItem, ShiroUser shiroUser, RequestNoteItemService requestNoteItemService) {
		this.requestNoteItem = requestNoteItem;
		this.shiroUser = shiroUser;
		this.requestNoteItemService = requestNoteItemService;
	}

	//需要实现Callable的Call方法
	public String call() throws Exception {
		synchronized (shiroUser.getUser().getOrganization().getAreaCode()) {
			requestNoteItemService.generatedData(requestNoteItem, shiroUser);
		}
		return "success";
	}

}




加载中
返回顶部
顶部