我想插入一条不存在的记录,两条记录都保存而不是一条记录,如果并发请求的时间相同,则只保存一条记录。
@GetMapping("/bookslot")
public void bookTicket() {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(run(slotService::method1));
executor.execute(run(slotService::method2));
executor.shutdown();
}
private Runnable run(FailableRunnable<Exception> runnable) {
return () -> {
try {
runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
};
}
存储库
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT e FROM Slot e WHERE e.time = :time")
Optional<Slot> findByTimeWithLock(@Param("time") LocalTime time);
服务等级
@Transactional
public void method1() throws InterruptedException {
saveSlot("sam", "07:00");
Thread.sleep(1000);
}
@Transactional
public void method2() throws InterruptedException {
saveSlot("Curran", "07:00");
Thread.sleep(1000);
}
@Transactional
public void saveSlot(String name, String newTime) {
LocalTime time = LocalTime.parse(newTime);
Optional<Slot> slotOptional = slotRepo.findByTimeWithLock(time);
if (!slotOptional.isPresent()) {
Slot newSlot = new Slot();
newSlot.setName(name);
newSlot.setTime(time);
slotRepo.save(newSlot);
}
}