访问数据库的规模服务的并发管理

发布于 2025-01-30 11:38:23 字数 984 浏览 2 评论 0原文

假设我们有一项服务公开休息端点(Spring Boot)。

此终点允许对产品进行评级。您可以随时重新评估。 此端点中发生的事情是检查您是否在之前进行了评分并更新最终评分。

我的问题是关于我们每秒收到一百万个请求到这项服务的情况,我们将水平扩展到100个实例。

这是动作的流程,因此很容易遵循:

var userReview = getUserReviewFromDb(UserId, ProductId);
var numberOfReviews = getNumberOfReviewsForProductFromDb(ProductId);
if (userReview == null) {
  // user didn't priorly review product
  // here we calculate new score of product and persist it
  var newReview = addNewReview(UserRating, UserID, ProductId);
  var newRating = calculateNewRating(ProductId, numberOfReviews + 1, UserRating);
  persisteNewProductRating(ProductId, newRating);
  return newRating;
} else {
  var newRating = calculateNewRating(ProductId, numberOfReviews, UserRating, UserId);
  persisteNewProductRating(ProductId, newRating);
  return newRating;
}

所以我的问题是,我们可以通过许多请求来执行该代码的问题,这会使评级有缺陷?由于它们都获得了以前的以前数量的副本,以便计算新的评论。很明显,我们可以,我不想仅仅锁定完整的DB,但这似乎是唯一的方法,要么是在交易中发送所有请求。

什么是管理这种并发的干净方法?我使用春季靴子。

Let's say we have a service exposing a REST endpoint (spring boot).

This endpoint allows for rating a product. You can re rate at any time.
What happens in this endpoint is checking if you rated before and update the final rating.

My question is regarding the situation when we have a million requests coming per second to this service we scaled horizontally to 100 instances.

This is the flow of actions so its easy to follow:

var userReview = getUserReviewFromDb(UserId, ProductId);
var numberOfReviews = getNumberOfReviewsForProductFromDb(ProductId);
if (userReview == null) {
  // user didn't priorly review product
  // here we calculate new score of product and persist it
  var newReview = addNewReview(UserRating, UserID, ProductId);
  var newRating = calculateNewRating(ProductId, numberOfReviews + 1, UserRating);
  persisteNewProductRating(ProductId, newRating);
  return newRating;
} else {
  var newRating = calculateNewRating(ProductId, numberOfReviews, UserRating, UserId);
  persisteNewProductRating(ProductId, newRating);
  return newRating;
}

So my question is, can we have issues where this code will be executed by many requests that would make the rating flawed ? since they all get a copy of number of previous previous in order to calculate new review. It seems obvious that we can, I wouldn't want to lock a full DB just but it seems like pretty much the only way, either that or send all requests in a transaction.

What are clean ways to manage this concurrency ? Im using Spring boot.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文