C++:使用poco库访问 redis

一、编译 poco

参考:https://blog.csdn.net/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 动态链接库的位置。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值