上传文件至 /

This commit is contained in:
myq 2025-02-18 10:37:52 +00:00
commit 1ae85ad6a7
2 changed files with 121 additions and 0 deletions

44
test-hiredis.cpp Normal file
View File

@ -0,0 +1,44 @@
#include <hiredis/hiredis.h>
#include <iostream>
#include <cstring> // 必须包含此头文件
void subscribe_thread() {
redisContext *c = redisConnect("127.0.0.1", 9090);
if (c == nullptr || c->err) {
std::cerr << "连接失败: " << (c ? c->errstr : "无上下文") << std::endl;
return;
}
// 订阅所有键空间事件
//PSUBSCRIBE __keyspace@0__:* 通配符*表示所有键空间事件
redisReply *reply = (redisReply *)redisCommand(c, "PSUBSCRIBE __keyspace@0__:*");
if (reply == nullptr || c->err) {
std::cerr << "订阅失败: " << c->errstr << std::endl;
freeReplyObject(reply);
redisFree(c);
return;
}
freeReplyObject(reply);
while (true) {
redisReply *msg_reply = nullptr;
if (redisGetReply(c, (void **)&msg_reply) != REDIS_OK) {
std::cerr << "接收消息错误" << std::endl;
break;
}
if (msg_reply && msg_reply->type == REDIS_REPLY_ARRAY
&& msg_reply->elements >= 3
&& strcmp(msg_reply->element[0]->str, "pmessage") == 0) {
std::cout << "事件频道: " << msg_reply->element[2]->str
<< ",操作类型: " << msg_reply->element[3]->str << std::endl;
}
freeReplyObject(msg_reply);
}
redisFree(c);
}
int main() {
subscribe_thread();
return 0;
}

77
test-redis++.cpp Normal file
View File

@ -0,0 +1,77 @@
#include <sw/redis++/redis++.h>
#include <iostream>
#include <thread>
#include <atomic>
#include <csignal>
using namespace sw::redis;
using namespace std;
atomic<bool> running{true};
// 信号处理函数 (用于优雅退出)
void signal_handler(int signal) {
if (signal == SIGINT) {
running = false;
cout << "\n程序即将退出..." << endl;
}
}
void keyspace_subscriber_thread(sw::redis::Redis &redis) {
try {
auto sub = redis.subscriber();
sub.on_message([](std::string channel, std::string msg) {
std::cout << "Received keyspace event from channel " << channel << ": " << msg << std::endl;
});
//突然又可以了
sub.subscribe("__keyspace@0__:key");
// 通配符订阅所有键空间事件 存在问题 不知道为何没有反应
//sub.psubscribe("__keyspace@0__:*");
// 开始接收消息
while (running) {
try {
sub.consume();
} catch (const Error &err) {
cerr << "Subscriber error: " << err.what() << std::endl;
}
}
} catch (const std::exception &e) {
std::cerr << "Subscriber error: " << e.what() << std::endl;
}
}
int main() {
try {
// 创建 Redis 连接
sw::redis::Redis redis("tcp://127.0.0.1:9090");
// 启动订阅者线程
std::thread sub_thread(keyspace_subscriber_thread, std::ref(redis));
// 设置键值对以触发键空间事件
while (running) {
std::string key = "key";
std::string value = "value";
redis.set(key, value);
std::cout << "Set " << key << " to " << value << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
redis.del(key);
std::cout << "Deleted " << key << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// 等待订阅者线程结束
sub_thread.join();
} catch (const std::exception &e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}