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 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
| #include "redis_examples.h" #include <chrono> #include <thread> #include <atomic>
RedisExamples::RedisExamples(const std::string &connection_string) : redis(connection_string) { }
bool RedisExamples::testConnection() { try { auto pong = redis.ping(); std::cout << "连接测试: " << pong << std::endl;
redis.set("test_key", "Hello, Redis!"); auto value = redis.get("test_key"); if (value) { std::cout << "获取测试值: " << *value << std::endl; }
redis.del("test_key"); return true; } catch (const Error &e) { std::cerr << "Redis 错误: " << e.what() << std::endl; return false; } }
void RedisExamples::stringOperations() { std::cout << "\n=== 字符串操作 ===" << std::endl;
try { redis.set("name", "Alice"); auto name = redis.get("name"); std::cout << "姓名: " << *name << std::endl;
redis.set("counter", "10"); redis.incr("counter"); auto counter = redis.get("counter"); std::cout << "计数器: " << *counter << std::endl;
redis.setex("temp_data", std::chrono::seconds(10), "临时数据");
std::unordered_map<std::string, std::string> data = { {"key1", "value1"}, {"key2", "value2"}, {"key3", "value3"}}; redis.mset(data.begin(), data.end());
std::vector<std::string> keys = {"key1", "key2", "key3"}; std::vector<OptionalString> values; redis.mget(keys.begin(), keys.end(), std::back_inserter(values));
for (size_t i = 0; i < values.size(); ++i) { if (values[i]) { std::cout << keys[i] << ": " << *values[i] << std::endl; } }
redis.del(keys.begin(), keys.end()); redis.del({"name", "counter"}); } catch (const Error &e) { std::cerr << "字符串操作错误: " << e.what() << std::endl; } }
void RedisExamples::listOperations() { std::cout << "\n=== 列表操作 ===" << std::endl;
try { std::string list_key = "my_list";
redis.rpush(list_key, "first"); redis.rpush(list_key, "second"); redis.lpush(list_key, "zero");
auto length = redis.llen(list_key); std::cout << "列表长度: " << length << std::endl;
std::vector<std::string> elements; redis.lrange(list_key, 0, -1, std::back_inserter(elements));
std::cout << "列表元素: "; for (const auto &elem : elements) { std::cout << elem << " "; } std::cout << std::endl;
auto popped = redis.lpop(list_key); if (popped) { std::cout << "弹出的元素: " << *popped << std::endl; }
redis.del(list_key); } catch (const Error &e) { std::cerr << "列表操作错误: " << e.what() << std::endl; } }
void RedisExamples::hashOperations() { std::cout << "\n=== 哈希操作 ===" << std::endl;
try { std::string hash_key = "user:1001";
redis.hset(hash_key, "name", "John Doe"); redis.hset(hash_key, "age", "30"); redis.hset(hash_key, "email", "john@example.com");
auto name = redis.hget(hash_key, "name"); if (name) { std::cout << "姓名: " << *name << std::endl; }
std::unordered_map<std::string, std::string> all_fields; redis.hgetall(hash_key, std::inserter(all_fields, all_fields.begin()));
std::cout << "所有字段:" << std::endl; for (const auto &field : all_fields) { std::cout << " " << field.first << ": " << field.second << std::endl; }
redis.hincrby(hash_key, "age", 1); auto new_age = redis.hget(hash_key, "age"); if (new_age) { std::cout << "新年龄: " << *new_age << std::endl; }
redis.del(hash_key); } catch (const Error &e) { std::cerr << "哈希操作错误: " << e.what() << std::endl; } }
void RedisExamples::setOperations() { std::cout << "\n=== 集合操作 ===" << std::endl;
try { std::string set_key = "my_set";
redis.sadd(set_key, "apple"); redis.sadd(set_key, "banana"); redis.sadd(set_key, "orange"); redis.sadd(set_key, "apple");
auto size = redis.scard(set_key); std::cout << "集合大小: " << size << std::endl;
std::vector<std::string> members; redis.smembers(set_key, std::back_inserter(members));
std::cout << "集合成员: "; for (const auto &member : members) { std::cout << member << " "; } std::cout << std::endl;
bool exists = redis.sismember(set_key, "apple"); std::cout << "apple 是否存在: " << (exists ? "是" : "否") << std::endl;
redis.del(set_key); } catch (const Error &e) { std::cerr << "集合操作错误: " << e.what() << std::endl; } }
void RedisExamples::transactionOperations() { std::cout << "\n=== 事务操作 ===" << std::endl;
try { auto tx = redis.transaction();
tx.set("tx_key1", "value1"); tx.set("tx_key2", "value2"); tx.incr("tx_counter");
tx.exec();
std::cout << "事务执行成功" << std::endl;
auto value1 = redis.get("tx_key1"); auto value2 = redis.get("tx_key2"); auto counter = redis.get("tx_counter");
if (value1) std::cout << "tx_key1: " << *value1 << std::endl; if (value2) std::cout << "tx_key2: " << *value2 << std::endl; if (counter) std::cout << "tx_counter: " << *counter << std::endl;
redis.del({"tx_key1", "tx_key2", "tx_counter"}); } catch (const Error &e) { std::cerr << "事务操作错误: " << e.what() << std::endl; } }
void RedisExamples::LuaTransaction() { std::cout << "\n=== Lua 事务回滚测试 ===" << std::endl;
try { redis.set("acc:X", "100"); redis.set("acc:Y", "50");
std::cout << "初始 - X: " << *redis.get("acc:X") << ", Y: " << *redis.get("acc:Y") << std::endl;
std::string tx_script = R"( local from = KEYS[1] local to = KEYS[2] local amount = tonumber(ARGV[1]) -- 先读取,不修改 local from_balance = tonumber(redis.call('GET', from)) local to_balance = tonumber(redis.call('GET', to)) -- 验证 if from_balance < amount then return "错误:余额不足" end -- 验证通过,执行转账 redis.call('DECRBY', from, amount) redis.call('INCRBY', to, amount) -- 最终验证(模拟业务规则) if amount > 80 then -- 违反规则,回滚操作 redis.call('INCRBY', from, amount) -- 退款 redis.call('DECRBY', to, amount) -- 扣回 return "错误:金额超过限制,已回滚" end return "成功" )";
auto result = redis.eval<std::string>(tx_script, {"acc:X", "acc:Y"}, {"90"}); std::cout << "转账结果: " << result << std::endl; std::cout << "最终 - X: " << *redis.get("acc:X") << ", Y: " << *redis.get("acc:Y") << std::endl;
redis.del({"acc:X", "acc:Y"}); } catch (const sw::redis::Error &e) { std::cerr << "错误: " << e.what() << std::endl; } }
void RedisExamples::pubsubOperations() { std::cout << "\n=== 发布订阅操作 ===" << std::endl;
try { sw::redis::ConnectionOptions conn_opts; conn_opts.host = "127.0.0.1"; conn_opts.port = 6382; conn_opts.socket_timeout = std::chrono::seconds(1);
sw::redis::ConnectionPoolOptions pool_opts; pool_opts.size = 1;
auto redis_ptr = std::make_shared<sw::redis::Redis>(conn_opts, pool_opts);
std::thread subscriber_thread([redis_ptr]() { try { auto sub = redis_ptr->subscriber();
sub.on_message([](std::string channel, std::string msg) { std::cout << "[订阅者] 收到消息 - 频道: " << channel << ", 消息: " << msg << std::endl; });
sub.subscribe("test_channel");
auto end_time = std::chrono::steady_clock::now() + std::chrono::seconds(30); while (std::chrono::steady_clock::now() < end_time) { try { sub.consume(); } catch (const sw::redis::TimeoutError &e) { continue; } }
std::cout << "[订阅者] 监听时间到,正常退出" << std::endl; } catch (const Error &e) { std::cerr << "订阅错误: " << e.what() << std::endl; } });
std::this_thread::sleep_for(std::chrono::milliseconds(100));
redis_ptr->publish("test_channel", "Hello from publisher!"); redis_ptr->publish("test_channel", "Second message");
subscriber_thread.detach();
std::cout << "主线程继续执行,订阅线程在后台运行30秒后自动退出" << std::endl; } catch (const Error &e) { std::cerr << "发布订阅错误: " << e.what() << std::endl; } }
void RedisExamples::pipelineBasic() { std::cout << "\n=== Pipeline 基本使用 ===" << std::endl;
try { auto pipe = redis.pipeline();
pipe.set("pipeline_key", "pipeline_value"); pipe.get("pipeline_key"); pipe.incr("pipeline_counter"); pipe.hset("pipeline_hash", "field", "value");
auto replies = pipe.exec();
std::cout << "SET 结果: " << replies.get<bool>(0) << std::endl;
auto value = replies.get<sw::redis::OptionalString>(1); if (value) { std::cout << "GET 结果: " << *value << std::endl; }
std::cout << "INCR 结果: " << replies.get<long long>(2) << std::endl; std::cout << "HSET 结果: " << replies.get<bool>(3) << std::endl; } catch (const Error &e) { std::cerr << "Pipeline 错误: " << e.what() << std::endl; } }
|