1
我有一個調度程序與多個線程更新我的表中的行。我試圖使用「更新跳過鎖定」,但由於某種原因,而不是找到下一個無人認領的行,每個線程選擇並更新相同的一個。 我有一個表「計數器」與「ID」和「計數器」列。Postgres「跳過鎖定」與Spring JDBC
CounterRepository.java
@Repository
public class CounterRepository {
private final JdbcTemplate jdbc;
public CounterRepository(JdbcTemplate jdbc) {this.jdbc = jdbc;}
@Transactional
void update() {
Integer id = jdbc.queryForObject("SELECT id FROM counter ORDER BY counter LIMIT 1 FOR UPDATE SKIP LOCKED;", Integer.class);
Integer counter = jdbc.queryForObject("SELECT counter FROM counter WHERE id = ?", Integer.class, id);
jdbc.update("UPDATE counter set counter = ? WHERE id = ?", 5 - counter, id);
}
}
DbAsyncUpdateApplication.java
@EnableAsync
@EnableScheduling
@SpringBootApplication
public class DbAsyncUpdateApplication {
@Bean(name = "threadPoolTaskExecutor")
public ScheduledExecutorService taskScheduler() throws InterruptedException {
return Executors.newScheduledThreadPool(5);
}
public static void main(String[] args) {
SpringApplication.run(DbAsyncUpdateApplication.class, args);
}
}
Scheduler.java
@Service
public class Scheduler {
private final CounterRepository repository;
public Scheduler(CounterRepository repository) {this.repository = repository;}
@Scheduled(fixedRate = 1000)
public void start() {
repository.update();
}
}
您使用的是什麼交易級別?您需要在行上讀取鎖以使邏輯工作。 – Voo
@Voo它的默認閱讀承諾 –
那麼你知道爲什麼這是行不通的。 – Voo