77 lines
2.2 KiB
C++
77 lines
2.2 KiB
C++
#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;
|
|
}
|