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){ }
}
}
我的问题是我如何在交易中运行可运行的作业?
只要事务是线程绑定的,将updateCache()
注释为@Transactional
将不起作用。
答案 0 :(得分:1)
不要那样安排,使用Spring的scheduling support。
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 />
。有关更多配置选项,另请参阅前面提到的链接。