湿胸你好,今天我测试了一下Data-JPA,想测试一下锁,比如用户注册,当邮箱不存在时,添加数据库。
Repository层
```
public interface UserRepository extends JpaRepository<User, Integer> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
Optional<User> findByEmail(String email);
}
```
Service层
```
@Transactional
public User signup(String email, String password) {
Optional<User> userExists = userRepository.findByEmail(email);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (!userExists.isPresent()) {
User user = new User();
user.setEmail(email);
user.setPassword(password);
return userRepository.save(user);
}
```
UnitTest
```
@Test
public void signupTest() {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.execute(() -> {
User user = userService.signup("123", "123");
if (user != null) {
log.info("用户注册成功");
}
});
pool.execute(() -> {
User user = userService.signup("123", "123");
if (user != null) {
log.info("用户注册成功");
}
});
// 这里加上个10秒的sleep
}
```
数据库仍然会插入两条数据。
SpringCloud组件实现微服务,【已升级Finchley.Release】
了解课程