0
  1. 有需要按 cron 计划完成的工作
  2. 必须在 spring boot 应用程序启动时执行与作业中相同的逻辑,因此使用 @PostConstruct 方法
  3. 使用 Shedlock,因为它计划在多个实例中运行应用程序

问题是:如何使 @PostConstruct 方法中的逻辑仅在一个实例中调用而不在其他实例中调用?

我的代码示例:

@Component
@AllArgsConstructor
public class TestJob {

    private TestService testService;

    @PostConstruct
    public void init() {
        testService.upload();
    }
    
    @Scheduled(cron = "${cron}")
    @SchedulerLock(name = "uploadJob", lockAtMostFor = "${lockAtMostFor}")
    public void execute() {
        testService.upload();
    }
}
4

1 回答 1

0

如果您将该@PostConstruct方法放到不同的服务并调用该execute()方法,它应该可以工作。

原因是 ShedLock 默认使用 Spring AOP,它将标记的每个方法包装@SchedulerLock在执行锁定的方面。如果您在同一个类中调用另一个方法,通常不会应用 Spring AOP。

于 2021-05-18T17:55:26.457 回答