保存事件时的竞争条件

发布于 2025-01-14 04:27:03 字数 533 浏览 2 评论 0原文

我有两个不同的端点,例如:

endpoint1 => /api/user
endpoint2 => /api/user/roles

想象一下这两个端点同时调用相同的方法。

public List activeRoles(userId) {
   var roles = repository.findAllRolesOfUser(userId);

   if (roles == null) {
      var role = new Role("DEFAULT", userId);
      repository.save(role);
      
      return Arrays.asList(role)
   } else {
      return roles;
   }
}

当我同时从端点 1 和端点 2 调用 activeRoles(userId) 方法时,它会导致竞争条件,并且在数据库中创建两次“DEFAULT”角色。有办法避免吗?

注意:我不能使用唯一约束。

I have two different endpoints like:

endpoint1 => /api/user
endpoint2 => /api/user/roles

Imagine that these two endpoints call same method at the same time.

public List activeRoles(userId) {
   var roles = repository.findAllRolesOfUser(userId);

   if (roles == null) {
      var role = new Role("DEFAULT", userId);
      repository.save(role);
      
      return Arrays.asList(role)
   } else {
      return roles;
   }
}

When I call activeRoles(userId) method from endpoint1 and endpoint2 at the same time, it causes race condition and "DEFAULT" role is created twice in the database. Is there a way to avoid it?

Note: I cannot use unique constraint.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

娇妻 2025-01-21 04:27:03

在java中使用同步

public List activeRoles(userId) {
   var roles = repository.findAllRolesOfUser(userId);

   if (roles == null) {
      var role = new Role("DEFAULT", userId);
      save(role);
      
      return Arrays.asList(role)
   } else {
      return roles;
   }
}

private syncronized void save(data) {
     var role = repository.findBy(...);
     
     if (!role) {
        repository.save(data);
     }
}

Use syncronized in java.

public List activeRoles(userId) {
   var roles = repository.findAllRolesOfUser(userId);

   if (roles == null) {
      var role = new Role("DEFAULT", userId);
      save(role);
      
      return Arrays.asList(role)
   } else {
      return roles;
   }
}

private syncronized void save(data) {
     var role = repository.findBy(...);
     
     if (!role) {
        repository.save(data);
     }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文