【4】cpp_redis hello world

本文介绍如何使用cpp_redis客户端在Windows环境下与Redis服务器交互。包括启动网络库、连接Redis、发送及接收数据等步骤,并展示了完整的示例代码。

【1】cpp_redis (Windows C++ Redis客户端)(C++11实现)官方最新源码编译
正文如下

下面的代码展示的一个完整的cpp_redis发送字符串并取回字符串的完整过程。包括如下几个步骤:

1 启动Windowst通信库WSA

2 连接redis服务端

3 发送数据给redis

4接收数据给redis

5 停止Windows通讯库WSA

6 cpp_redis通过异常来做错误处理:所以一个业务模块如果只处理一个问题的话,应该把异常放到外围,内部各种操作,最后一起处理异常,这样代码比较好理解。

7 所有通信的成功与不成功都应该依赖于异常

8 所有的业务数据合理与不合理都应该依赖于is_###()来判断


代码(Hello World):

#include <cpp_redis/cpp_redis>
#include <iostream>
#include "TestRedis.h"
using namespace std;

#ifdef _WIN32
#include <Winsock2.h>
#endif /* _WIN32 */
#pragma comment( lib, "ws2_32.lib")//最好的方法是包含在项目属性中,因为那样可以根据Debug、Release、x86、x64来区分。这里仅仅是为了突出引用了这个库写在这里 

bool StartWSA(void)
{
	//! Windows netword DLL init
	WORD version = MAKEWORD(2, 2);
	WSADATA data;

	if (WSAStartup(version, &data) != 0)
	{
		std::cerr << "WSAStartup() failure" << std::endl;
		return false;
	}
	return true;
}
void StopWSA(void)
{
	WSACleanup();
}

int main(void) 
{
	//启动Windows网络通信库
	if (!StartWSA())
	{
		return -1;
	}
	try
	{
		//! Enable logging
		cpp_redis::active_logger = std::unique_ptr<cpp_redis::logger>(new cpp_redis::logger);
		cpp_redis::redis_client client;
		client.connect("127.0.0.1", 6379, [](cpp_redis::redis_client&)
		{
			std::cout << "client disconnected (disconnection handler)" << std::endl;
		});

		client.set("hello", "Hello World!");
		client.get("hello", [](cpp_redis::reply& reply)
		{
			std::cout << "get hello: " << reply << std::endl;
		});

		// synchronous commit, no timeout
		client.sync_commit();
	}
	catch (cpp_redis::redis_error e)
	{
		std::cout << e.what() << endl;
	}


	//关闭Windows网络通信库
	StopWSA();

  return 0;
}

输出:我们给redis不同的外部环境,看看跑出来的效果

(1)关闭redis服务:连接失败被捕获并显示出来


(2)启动redis服务:执行效果


(3)如果我们发送的hello,取的时候写成了首字母大写Hello会输出:


之所以会输出(nil)是因为reply的输出操作符重载中定义的:

  case cpp_redis::reply::type::null:
    os << std::string("(nil)");
    break;

客户端查看:


下篇文章重点讲一下返回值的结构reply

在 C++ 中连接 Redis,最常用的方法是使用第三方库 **hiredis**(Redis 官方推荐的 C 客户端),然后通过 C++ 封装或使用基于 hiredis 的 C++ 封装库如 **hiredis++** 或 **redis-plus-plus**。下面我将详细介绍如何使用 **redis-plus-plus**(现代、易用、功能完整)来连接和操作 Redis。 --- ### ✅ 推荐方案:使用 `redis-plus-plus` `redis-plus-plus` 是一个现代 C++ (C++11 及以上) Redis 客户端,基于 hiredis 构建,支持同步/异步操作、连接池、Pipeline、发布订阅等。 --- ## 一、安装依赖 ### 1. 安装 hiredisredis-plus-plus #### Ubuntu / Debian: ```bash # 安装编译工具链 sudo apt-get update sudo apt-get install build-essential git cmake # 克隆并编译安装 hiredis git clone https://github.com/redis/hiredis.git cd hiredis make && sudo make install sudo ldconfig # 更新共享库缓存 # 克隆并安装 redis-plus-plus cd .. git clone https://github.com/sewenew/redis-plus-plus.git cd redis-plus-plus mkdir build && cd build cmake .. make && sudo make install ``` > 注意:确保 `libhiredis.so` 和 `libredis++.so` 被正确安装到系统路径。 --- ## 二、C++ 示例代码:连接 Redis 并执行基本操作 ```cpp #include <iostream> #include <sw/redis++/redis++.h> int main() { try { // 创建 Redis 连接对象(默认连接到 127.0.0.1:6379) sw::redis::ConnectionOptions connection_options; connection_options.host = "127.0.0.1"; // Redis 地址 connection_options.port = 6379; // 端口 connection_options.db = 0; // 数据库编号 // 如果有密码,取消下一行注释: // connection_options.password = "yourpassword"; sw::redis::Redis redis(connection_options); // SET 操作 redis.set("name", "Alice"); std::cout << "Set key 'name' to 'Alice'" << std::endl; // GET 操作 auto val = redis.get("name"); // 返回 OptionalString if (val) { std::cout << "Get name: " << *val << std::endl; } else { std::cout << "Key 'name' not found" << std::endl; } // INCR 操作 redis.set("counter", "100"); long long cnt = redis.incr("counter"); std::cout << "Counter after INCR: " << cnt << std::endl; // LPUSH + LRANGE redis.lpush("mylist", {"world", "hello"}); std::vector<std::string> list; redis.lrange("mylist", 0, -1, std::back_inserter(list)); std::cout << "List content: "; for (const auto& s : list) std::cout << s << " "; std::cout << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; } ``` --- ## 三、编译命令 假设你的源文件名为 `redis_demo.cpp`: ```bash g++ -std=c++11 redis_demo.cpp -lredis++ -lhiredis -o redis_demo ``` 运行程序: ```bash ./redis_demo ``` 输出示例: ``` Set key 'name' to 'Alice' Get name: Alice Counter after INCR: 101 List content: hello world ``` --- ## 四、解释说明 | 组件 | 作用 | |------|------| | `ConnectionOptions` | 配置 Redis 连接参数(host, port, db, password 等) | | `Redis` 类 | 提供所有 Redis 命令接口(set/get/incr/lpush 等) | | `redis.get()` | 返回 `Optional<std::string>`,可用 `if(val)` 判断是否存在 | | 异常处理 | 所有错误抛出 `std::exception` 子类,建议用 try-catch 包裹 | --- ## 五、高级功能(可选) ### 使用连接池(适用于多线程服务) ```cpp sw::redis::ConnectionPoolOptions pool_opts; pool_opts.size = 3; // 连接池大小 sw::redis::Redis redis(connection_options, pool_opts); ``` ### 发布/订阅 示例 ```cpp auto sub = redis.subscriber(); sub.on_message([](const std::string& channel, const std::string& msg) { std::cout << "Received: " << msg << " from channel: " << channel << std::endl; }); sub.subscribe("chat"); // 在另一个终端用 redis-cli 发布消息测试: // PUBLISH chat "Hello Redis" ``` --- ## 六、常见问题排查 - ❌ 报错 `undefined reference to redis++`:确认是否链接了 `-lredis++ -lhiredis` - ❌ 连接拒绝:检查 Redis 是否运行 `redis-server` - ❌ 找不到头文件:确认 `#include <sw/redis++/...>` 路径正确,CMake 或编译器能找到安装路径 - ✅ 推荐使用 CMake 管理项目(见下文扩展) --- ### 📦 使用 CMake 的 `CMakeLists.txt` 示例 ```cmake cmake_minimum_required(VERSION 3.10) project(redis_cpp_example) set(CMAKE_CXX_STANDARD 11) find_package(hiredis REQUIRED) find_package(redis++ REQUIRED) add_executable(redis_demo redis_demo.cpp) target_link_libraries(redis_demo PRIVATE hiredis::hiredis redis++::redis++) ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++程序员Carea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值