如何强制 Rails 通过连接将事务同步到 MySQL 表?

发布于 2024-09-16 11:05:55 字数 328 浏览 0 评论 0原文

我有一个高流量网站,在“点击量”表中记录网络点击量。存在适当的逻辑,以便丢弃重复的命中(其中,对于本示例的目的,将命中定义为重复的定义是任意的)。

问题:当多个 Web 服务器运行时(针对同一个数据库),两个或多个命中可能同时到达不同的 Web 服务器,并且从每个服务器的角度来看,它们都不是重复的(而它们是通过单个服务器序列化的)但第一个应该被丢弃)。因此,所有这些都被写入 Hits 表中。

在不更改数据库模式以强制 Hits 表中字段唯一性的情况下,如何强制 Rails 将事务同步到数据库以保证不写入重复项?根据文档,ActiveRecord 事务仅在每个连接的基础上强制执行,这还不够好(据我所知)。

I have a high-traffic site that records web hits in a table, Hits. There's logic in place so that duplicate hits are discarded (where the definition of what defines a hit as duplicate is arbitrary for the purposes of this example).

Problem: with multiple web servers running (against the same DB), two or more hits can arrive at the same time on different web servers and, from each server's perspective, none of them are duplicates (whereas were they serialized through a single server all but the first should be discarded). Hence, all of them get written to the Hits table.

Without altering the DB schema to force uniqueness on a field in the Hits table, how do I force Rails to synchronize the transaction to the database to guarantee that no duplicates are written? According to the documentation, ActiveRecord transactions are only enforced on a per-connection basis, which isn't good enough (as far as I can tell).

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

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

发布评论

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

评论(1

白首有我共你 2024-09-23 11:05:55

MySQL 中的事务始终是针对每个连接的,没有其他方法可以告诉您什么是原子操作。

我认为做到这一点的唯一方法是在整个表上放置锁或在架构级别上强制完整性。

Transactions in MySQL are always per-connection, there's no other way to tell what is an atomic operation.

I think the only way to do this is either by placing a lock on the whole table or to enforce the integrity on the schema level.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文