gpt4 book ai didi

java - 如何在另一个线程中启动事务?

转载 作者:行者123 更新时间:2023-11-30 07:38:30 24 4
gpt4 key购买 nike

Spring 4

我正在努力通过 ScheduledThreadPoolExecutor 实现可更新缓存。目前看起来如下:

public class MyService {

@Setter
private MyDao myDao;
//Immutable
private volatile Cache cache;

//Static factory method
public static MyService create(){
MyService retVal = new MyService();
cache = Cache.emptyCache();
updateCache();
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public int get(){
//Retrieving from cache
return cache.getNext();
}

private void updateCache() {
try{
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
//The runnable should be in a transaction.
Runnable updateCache;
//the runnable queries the MyDao,
//which in turn currently implemented as a DB-dao
//The cache is assigned after computation
ses.scheduleWithFixedDelay(updateCache, 0, 60, TimeUnit.SECONDS);
} catch (Throwable t){ }
}
}

我的问题是如何在事务中运行可运行作业?

只要事务是线程绑定(bind)的,将 updateCache() 注释为 @Transactional 将不起作用。

最佳答案

不要这样安排,使用 scheduling support Spring 。

public class MyService {

@Setter
private MyDao myDao;
//Immutable
private volatile Cache cache;

//Static factory method
public static MyService create(){
MyService retVal = new MyService();
cache = Cache.emptyCache();
updateCache();
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
public int get(){
//Retrieving from cache
return cache.getNext();
}

@Transactional
@Scheduled(fixedDelay=60000)
public void updateCache() {
//the runnable queries the MyDao,
//which in turn currently implemented as a DB-dao
//The cache is assigned after computation
}
}

然后添加 @EnableScheduling<task:annotation-driven /> 。另请参阅前面提到的链接以获取更多配置选项。

关于java - 如何在另一个线程中启动事务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35031711/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com