-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistributed_locks.cpp
More file actions
126 lines (109 loc) · 3.12 KB
/
Distributed_locks.cpp
File metadata and controls
126 lines (109 loc) · 3.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//
// Created by YeSho on 2024/10/18.
//
#include <hiredis/hiredis.h>
#include <string>
#include <chrono>
#include <thread>
#include <uuid/uuid.h>
#include <iostream>
// 生成唯一标识符
std::string generate_uuid() {
uuid_t uuid;
uuid_generate(uuid);
char uuid_str[37]; // 36 characters + null terminator
uuid_unparse(uuid, uuid_str);
return std::string(uuid_str);
}
class RedisDistributedLock {
public:
RedisDistributedLock(redisContext* context, const std::string& lock_key, int lock_timeout_ms = 10000)
: context_(context), lock_key_(lock_key), lock_timeout_ms_(lock_timeout_ms), locked_(false) {
uuid_ = generate_uuid();
}
// 尝试获取锁
bool lock() {
// 使用 SET 命令,并设置 NX 和 PX 选项
std::string command = "SET " + lock_key_ + " " + uuid_ + " NX PX " + std::to_string(lock_timeout_ms_);
redisReply* reply = (redisReply*)redisCommand(context_, command.c_str());
if (reply == nullptr) {
std::cerr << "Redis command failed\n";
return false;
}
bool success = false;
if (reply->type == REDIS_REPLY_STATUS && std::string(reply->str) == "OK") {
success = true;
locked_ = true;
}
freeReplyObject(reply);
return success;
}
// 释放锁
bool unlock() {
if (!locked_) {
return false;
}
// 使用 Lua 脚本确保原子性:检查值是否匹配,再删除
const char* lua_script =
"if redis.call('GET', KEYS[1]) == ARGV[1] then "
" return redis.call('DEL', KEYS[1]) "
"else "
" return 0 "
"end";
redisReply* reply = (redisReply*)redisCommand(context_, "EVAL %s 1 %s %s",
lua_script, lock_key_.c_str(), uuid_.c_str());
if (reply == nullptr) {
std::cerr << "Redis EVAL command failed\n";
return false;
}
bool success = false;
if (reply->type == REDIS_REPLY_INTEGER && reply->integer == 1) {
success = true;
locked_ = false;
}
freeReplyObject(reply);
return success;
}
~RedisDistributedLock() {
if (locked_) {
unlock();
}
}
private:
redisContext* context_;
std::string lock_key_;
std::string uuid_;
int lock_timeout_ms_;
bool locked_;
};
int main() {
// 连接到 Redis
redisContext* context = redisConnect("127.0.0.1", 6379);
if (context == nullptr || context->err) {
if (context) {
std::cerr << "Connection error: " << context->errstr << "\n";
redisFree(context);
} else {
std::cerr << "Connection error: can't allocate redis context\n";
}
return 1;
}
std::string lock_key = "my_distributed_lock";
RedisDistributedLock lock(context, lock_key, 5000); // 锁超时 5 秒
if (lock.lock()) {
std::cout << "Lock acquired!\n";
// 执行临界区代码
std::this_thread::sleep_for(std::chrono::seconds(2));
// 释放锁
if (lock.unlock()) {
std::cout << "Lock released!\n";
} else {
std::cout << "Failed to release lock.\n";
}
} else {
std::cout << "Failed to acquire lock.\n";
}
// 关闭 Redis 连接
redisFree(context);
return 0;
}