【发布时间】:2018-12-31 11:01:42
【问题描述】:
我有以下设置:
@Component
public class Scheduler {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
BatchService batchService;
@Scheduled(cron = "0 */1 * ? * *")
void tick() {
logger.info("Beginning of a batch tick");
batchService.refundNotAssignedVisits();
logger.info("End of the batch tick");
}
}
BatchService 包含以下内容:
@Service
public class BatchServiceImpl implements BatchService {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
VisitService visitService;
@Override
@Transactional
public void refundNotAssignedVisits() {
logger.info("Start automatic refund of past visits being assigned");
Set<Visit> visits = visitService.findRefundableVisits();
if(visits != null && visits.size() != 0) {
logger.info("Found " + visits.size() + " visits to refund with IDs: " + visits.stream().map(x -> x.getId().toString()).collect(Collectors.joining(", ")));
visits.forEach(x -> {
logger.info("Refunding visit with ID: " + x.getId());
try {
visitService.cancel(x);
logger.info("Visit successfully refunded!");
}
catch(Exception e) {
logger.error("Error while refunding visit...", e);
}
});
}
else {
logger.info("Found no visit to refund.");
}
logger.info("End of automatic refund");
}
}
而cancel 方法定义如下:
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public Visit cancel(Visit visit) throws Exception {
// Some business logic
}
出于业务目的,我需要 cancel 方法在每次调用中处理一个事务,目前,refundNotAssignedVisits 是 @Transactional 以启用 Hibernate 会话,因此我可以使用延迟加载cancel 方法中的相关实体。
这会导致诸如重复提交之类的问题,我想知道什么是实现我想要的好模式:有一个 @Scheduled 方法可以启用 Hibernate 会话,以便对另一个方法进行多次调用,每次调用一个事务.
【问题讨论】:
-
我没听错吧:目前
tick方法有可能同时运行两次,您想避免吗?
标签: java spring hibernate spring-scheduled