在 Meteor 中处理并发请求 [英] Dealing with concurrent requests in Meteor

查看:46
本文介绍了在 Meteor 中处理并发请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个问题,即用户可以在指定的时间限制内更新文档,如果他不这样做,服务器会这样做.

I'm dealing with a problem where a user can update a document within a specified time limit, and if he doesn't, the server will.

更新涉及增加一个值并将一个对象添加到文档数组中.我需要确保只有一个用户/服务器更新文档.两者都不是.

The update involves incrementing a value and adding an object to an array of a document. I need to ensure that only one of the user/server updates the document. Not both.

为确保发生这种情况,会运行一些检查以查看文档是否已更新,但有时用户和服务器会在完全相同的时间运行并且都通过检查,然后文档会更新两次.

To ensure this happens, some checks are run to see if the document has already been updated, but there are times where the user and server run at exactly the same time and both pass the checks and then the document is updated twice.

我一直在尝试许多不同的方法来解决这个问题,但我一直没能做到.我尝试实现类似于此的锁:http://en.wikipedia.org/wiki/Peterson%27s_algorithm 确保只更新一次,第二次更新失败,但我没有成功.有什么想法吗?

I've been trying many different ways of fixing this, but I haven't been able to. I tried implement a lock similar to this: http://en.wikipedia.org/wiki/Peterson%27s_algorithm to ensure that only one update will happen and the second update will fail, but I haven't been successful. Any ideas?

推荐答案

为确保发生这种情况,会运行一些检查以查看文档是否已更新,但有时用户和服务器会在完全相同的时间运行并且都通过检查,然后文档会更新两次.

To ensure this happens, some checks are run to see if the document has already been updated, but there are times where the user and server run at exactly the same time and both pass the checks and then the document is updated twice.

您可以通过使用 MongoDB 更新查询来实现此目的,该查询同时检查值是否已更新并更新它.像这样:

You can achieve this by using a MongoDB update query that simultaneously checks if the value has been updated and updates it. Like this:

var post = Posts.findOne("ID");
// ... do some stuff with the post ...
Posts.update({counter: post.counter}, {$push: {items: newItem}, $inc: {counter: 1}});

如您所见,在一个查询中,我们都检查计数器并将其递增 - 因此,如果其中两个查询一个接一个地运行,只有一个会实际更新文档(因为计数器不再匹配).

As you can see, in one query we both check the counter and increment it - so if two of these queries run one right after another only one will actually update the document (since the counter won't match anymore).

这篇关于在 Meteor 中处理并发请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆