Redis集群中的二次投票问题探讨(redis集群 二次投票)

Recent,when using Redis in various projects, it is sometimes necessary to use the Redis Cluster mode to ensure service stability. In this case, when using it in voting, there will be a problem of ‘second vote’. Now let’s explore it.

First of all, let’s define the so-called ‘second vote’. When using Redis Cluster as the medium for voting, due to the distributed architecture of the Redis Cluster, the same data of different voting nodes may be distributed to different master and slave nodes of the same Redis Cluster. In this case, if a voting is re-issued, the same data may be written to the master and slave nodes of the same Redis Cluster. At this point, when the data is searched, the voting data of the same user ID appears twice, resulting in the so-called duplicate vote problem.

Therefore, in order to solve this problem, we need to consider how to avoid duplicate votes when using the Redis Cluster. Among them, there are two simple and feasible solutions.

The first is to use pipe buffering. When a user votes, it is necessary to determine whether the user ID has been written in all the master and slave nodes of the corresponding Redis Cluster. If it has not been written, it can be written in batches. For example, you can use the following code:

MULTI — open the buffer pool set userId 1 — Set key-value prs EXEC — Submit the buffer pool

Through this code, we can ensure that a data is written to the Redis Cluster only once.

The second is to use Redlock distributed mutex lock. When using Redis Cluster in voting, we need to use distributed locks in the voting process, such as the Redlock distributed mutex lock. This lock can ensure that the same user ID is written only once to the Redis Cluster. The code is as follows:

//Defines the function used to obtn distributed locks const Redlock = require(“redlock”); const lock = new Redlock([client.client1(), client.client2(), client.client3()], {retryCount: 10}); //Information required when obtning a lock const id = “userId” const resource = [“voting”,id].join(“:”); const ttl = 10000 const attemptLock = function () { lock.lock(resource, ttl).then(function (votingLock) { //Read data set userId 1 // Write data votingLock.unlock().catch(function (err) { //Force to unlock }) }) } // Call the attemptsLock function to lock attemptLock();

Using Redlock distributed mutex lock, we can ensure that the same user ID is written to the Redis Cluster only once, thereby avoiding the ‘second vote’ problem.

In summary, when using Redis cluster in voting services, in order to avoid the ‘second vote’ problem, we can use the pipe buffering or Redlock distributed mutex lock to ensure that only one voting data of the same user ID is written to all the master and slave nodes of the Redis Cluster.


数据运维技术 » Redis集群中的二次投票问题探讨(redis集群 二次投票)