C++ 实现 redis 发布订阅 --- 使用 hiredis 同步API(二)

做服务端开发基本都会用到redis,java调用redis就简单了,教程很多,库也都是现成的,多数会选择jedis库吧,但是c++调用redis就麻烦一点,基本都要自己编译才行。虽然支持c++的redis库也很多,但是用哪个呢?找了一下资料,发现hiredis库大家用的比较多,于是在开发过程中用了一下。还谈不上多深入,本文只讲些简单用法。

       首先下载编译hiredis,访问https://github.com/redis/hiredis下载hiredis库源码,我的编译环境为ubuntu14,解压hiredis源码后,终端下进入源码目录,然后输入make命令编译即可,编译后将分别得到静态及动态库文件:libhiredis.a / libhiredis.so,然后结合头文件就可以在工程中使用redis了。项目中我用是静态库libhiredis.a及头文件:hiredis.h,read.h,sds.h,使用静态库还是动态库,因人而异。

       1. 下面是根据服务器ip、端口及密码,连接redis代码示例:

void redisConnect(string serverAddr, uint16_t port, string password)
{
    LOG_INFO << "开始连接redis服务器..." << serverAddr << ":" << port;

    // 连接
    timeval timeout = { 3, 500000 };
    redis_ctx_ = redisConnectWithTimeout(serverAddr.c_str(), port, timeout);
    if (redis_ctx_ == NULL || redis_ctx_->err)
    {
        if (redis_ctx_ != NULL)
        {
            LOG_INFO << "连接异常: " << redis_ctx_->errstr;
            redisFree(redis_ctx_);
            redis_ctx_ = NULL;
        }
        else
        {
            LOG_INFO << "连接异常: redis context初始化出错";
        }

        // todo 延迟30秒重新连接redis服务器
        return;
    }
    else
    {
        LOG_INFO << "连接redis服务器成功..." << serverAddr << ":" << port;
    }

    // 验证
    redis_reply_ = (redisReply *)redisCommand(redis_ctx_, "auth %s", password.c_str());
    if (redis_reply_->type == REDIS_REPLY_ERROR)
    {
        LOG_INFO << "Authentication failure";
    }
    else
    {
        LOG_INFO << "Authentication success";
    }
    freeReplyObject(redis_reply_);
}

 结合输出日志一起看,代码也容易懂。上面的延迟30秒重连机制需要自己设计。
       2. 分发数据至redis服务器(redis发布订阅模式):

       主要调用redisCommand(),按照指定格式填写命令参数,就可以执行各种redis命令。这里不再一一列举。不过hiredis在实际应用中性能如何,还有待验证。

void distributeRedisMessage(const string &content, const string &topic)
{
    if (redis_ctx_ == NULL)
    {
        return;
    }

    redis_reply_ = (redisReply *)redisCommand(redis_ctx_, "publish %s %s", topic.c_str(), content.c_str());
    if (redis_reply_ != NULL)
    {
        if (redis_reply_->type == REDIS_REPLY_ERROR)
        {
            LOG_INFO << "命令发送失败: " << redis_reply_->type << " " << redis_reply_->str;
        }
        freeReplyObject(redis_reply_);
    }
    else
    {
        LOG_INFO << "与redis服务器连接异常, 命令发送失败: " << redis_ctx_->err << " " << redis_ctx_->errstr;
        redisFree(redis_ctx_);
        redis_ctx_ = NULL;

        // todo 延迟30秒重新连接redis服务器
    }
}

当然,上面都是封装好的方法,还要记得声明redisContext *redis_ctx_及redisReply *redis_reply_,并记得初始化。

       工作中也会写些java服务端程序,jedis我也在用,这里顺便提一下前几天遇到的一个jedis报错,很不好查。错误提示如下:

Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool.

       查来查去,最后发现是配置文件问题,以下图为例:

                                                                   

每个值后面不能有空格,这个很隐蔽,去掉每个值后面的空格,启动程序就一切正常了。

同步API 发布订阅 简单实例:

 subscribe

#include <iostream>
#include <cstdlib>
#include <string>
#include "hiredis\hiredis.h"
 
using namespace std;
int main()
{
	//1、连接Redis服务器
	redisContext *context = redisConnect("127.0.0.1", 6379);
	if (context->err)
	{
		std::cout << "can not connect to redisserver: 127.0.0.1,port:6379" << endl;
		std::cout << "reason:" << context->errstr << endl;
		redisFree(context);
		context = NULL;
		return 0;
	}
 
	//2、校验密码
	char *auth = "test123";
	redisReply *reply = (redisReply *)redisCommand(context, "AUTH %s", auth);
	if (NULL == reply)
	{
		std::cout << "wrong password!" << endl;
		freeReplyObject(reply);
		redisFree(context);
		context = NULL;
		return 0;
	}
	freeReplyObject(reply);
 
	//3、选择数据库 - 不选择也可
	reply = (redisReply *)redisCommand(context, "SELECT %d", 1);
	if (NULL == reply || REDIS_REPLY_ERROR == reply->type)
	{
		std::cout << "select failed!" << endl;
		freeReplyObject(reply);
		redisFree(context);
		context = NULL;
		return 0;
	}
 
	std::cout << "subscribe redischat!" << endl;
 
	//4、订阅消息  可以订阅多个消息 PSUBSCRIBE pattern 
	reply = (redisReply *)redisCommand(context, "SUBSCRIBE %s", "redischat");
	if (NULL == reply||reply->type != REDIS_REPLY_ARRAY)//订阅成功返回一个数组标识
	{
		std::cout << "subscribe failed!" << endl;
		freeReplyObject(reply);
		redisFree(context);
		context = NULL;
		return 0;
	}
	freeReplyObject(reply);
 
	//5、阻塞等待订阅消息
	while (true)
	{
		void *_reply = nullptr;
		if (redisGetReply(context, &_reply) != REDIS_OK)
		{
			continue;
		}
		reply = (redisReply*)_reply;
		for (int nIndex = 0; nIndex < reply->elements; nIndex++)
		{
			std::cout << nIndex + 1 << ")";
			std::cout << reply->element[nIndex]->str << std::endl;
		}
		freeReplyObject(reply);
		std::cout << "***************" << std::endl;
	}
	redisFree(context);
	context = NULL;
	return 0;
}

publish

#include <iostream>
#include <cstdlib>
#include <string>
#include "hiredis\hiredis.h"
using namespace std;
int main()
{
	//1、连接服务器
	redisContext *context = redisConnect("127.0.0.1", 6379);
	if (context->err)
	{
		std::cout << "can not connect to redisserver: 127.0.0.1,port:6379" << endl;
		std::cout << "reason:" << context->errstr << endl;
		redisFree(context);
		context = NULL;
		return 0;
	}
 
	//2、校验密码
	char *auth = "test123";
	redisReply *reply = (redisReply *)redisCommand(context, "AUTH %s", auth);
	if (NULL == reply)
	{
		std::cout << "wrong password!" << endl;
		redisFree(context);
		context = NULL;
		return 0;
	}
	freeReplyObject(reply);
 
	//3、选择数据库
	reply = (redisReply *)redisCommand(context, "SELECT %d", 1);
	if (NULL == reply || REDIS_REPLY_ERROR == reply->type)
	{
		std::cout << "select failed!" << endl;
		redisFree(context);
		context = NULL;
		return 0;
	}
	std::cout << "publish redischat!" << endl;
 
	//4、推送消息
	while (true)
	{
		std::string Message;
		char s[1024];
		memset(s, 0, 1024);
		cin >>s;
		Message.append(s);
		reply = (redisReply *)redisCommand(context, "publish %s %s", "redischat", Message.c_str());
		if (NULL == reply || reply->type != REDIS_REPLY_INTEGER)//成功推送几个就会有几个 integer
		{
			break;
		}
		freeReplyObject(reply);
	}
	if (reply!=NULL)freeReplyObject(reply);
	redisFree(context);
	context = NULL;
	return 0;
}
#endif

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值