一、编译 poco
参考:https://blog.youkuaiyun.com/fengbohello/article/details/118335212
二、使用 Poco/Redis/Client 访问 redis
确保 redis 服务已开启,redis 服务器信息如下:
host : 127.0.0.1
port : 6379
演示代码如下:
//redis-client.cpp
#include <Poco/Redis/Client.h>
#include <Poco/Redis/Command.h>
#include <iostream>
int main(int argc, char **argv)
{
Poco::Redis::Client rds = Poco::Redis::Client("127.0.0.1", 6379);
Poco::Redis::Command setCmd = Poco::Redis::Command::set("a", "av");
auto sres = rds.execute<std::string>(setCmd);
std::cout << "--- set res : " << sres << std::endl;
Poco::Redis::Command hsetCmd = Poco::Redis::Command::hset("b", "bk", "bv");
auto ires = rds.execute<Poco::Int64>(hsetCmd);
std::cout << "--- hset res : " << ires << std::endl;
Poco::Redis::Command gCmd = Poco::Redis::Command::get("a");
auto gres = rds.execute<Poco::Redis::BulkString>(gCmd);
std::cout << "--- get a : " << gres << std::endl;
Poco::Redis::Command hgCmd = Poco::Redis::Command::hget("b", "bk");
auto hgres = rds.execute<Poco::Redis::BulkString>(hgCmd);
std::cout << "--- hget b : " << hgres << std::endl;
return 0;
}
上述代码首先执行了 set命令和hset命令,然后执行了get 命令和 hget 命令。
三、编译及运行
编译,得到目标文件redis-client:
g++ -o redis-client redis-client.cpp --std=c++17 -l PocoRedis -l PocoNet -l PocoFoundation -I /usr/local/include/
运行目标文件 redis-client(确保 redis-server已开启):
$ LD_LIBRARY_PATH=/usr/local/lib/ ./redis-client
--- set res : OK
--- hset res : 0
--- get a : av
--- hget b : bv
环境变量 LD_LIBRARY_PATH 用于在运行时指定 poco 动态链接库的位置。