redis实现的发送订阅系统,即pub-sub,这部分的的代码比较少,也方便分析。在这只将会分析下普通的pub-sub(会忽略掉Pattern-matching subscriptions),以此来简述一个pubsub系统是如何实现的。

在redis主要有介绍redis的pub-sub,在开始之前, 需要知道redis的pubsub的几个命令:

SUBSCRIBE first second //订阅两个channel,分别是first和second

PUBLISH secondHello   //发送方向channel是second的发送"hello"消息

UNSUBSCRIBE      //取消之前订阅的所有channel

下面来看看在redis的Pubsub.c代码中对这些命令的实现。

首先看看subscribe的实现:

voidsubscribeCommand(redisClient *c) {
int j; for (j = 1; j < c->argc; j++)
//客户端订阅多个channel,对于需要订阅的每个channel都执行该函数
pubsubSubscribeChannel(c,c->argv[j]);
} /* Subscribe aclient to a channel. Returns 1 if the operation succeeded, or
* 0 if the client was already subscribed tothat channel. */
intpubsubSubscribeChannel(redisClient *c, robj *channel) {
struct dictEntry *de;
list *clients = NULL;
int retval = 0; //c->pubsub_channels是一个redis自己实现的hash表,这不是我们的重点,就不展开说了
//dictAdd向hash表中增加一个key为channel,value为null的键值对
/* Add the channel to the client ->channels hash table */
if(dictAdd(c->pubsub_channels,channel,NULL) == DICT_OK) {
retval = 1;
incrRefCount(channel);
//从服务端查找当前需要订阅的channel是否已经在服务端登记过
//没有登记过,则创建一个列表作为channel的值,并记录到服务端
//也就是意味着服务端是通过这个列表来得知这个channel是被哪些客户端订阅过了
//登记过,则取出在服务端,channel所对应的客户端列表
/* Add the client to the channel ->list of clients hash table */
de =dictFind(server.pubsub_channels,channel);
if (de == NULL) {
clients = listCreate();
dictAdd(server.pubsub_channels,channel,clients);
incrRefCount(channel);
} else {
clients = dictGetVal(de);
}
//向这个channel所对应的记录客户端的列表的尾部插入当前客户端,
//这样服务端就当前客户端订阅了这个channel
listAddNodeTail(clients,c);
}
/* Notify the client */
addReply(c,shared.mbulkhdr[3]);
addReply(c,shared.subscribebulk);
addReplyBulk(c,channel);
addReplyLongLong(c,dictSize(c->pubsub_channels)+listLength(c->pubsub_patterns));
return retval;
} //在看看pub的实现:
voidpublishCommand(redisClient *c) {
//发送则向某个channel发送消息,如 PUBLISH second Hello
//c->args[1]就是channel second,第二个参数就是要发送的消息Hello
int receivers =pubsubPublishMessage(c->argv[1],c->argv[2]);
addReplyLongLong(c,receivers);
} /*Publish a message */
intpubsubPublishMessage(robj *channel, robj *message) {
int receivers = 0;
struct dictEntry *de;
listNode *ln;
listIter li; //从服务端找到订阅了这个channel的客户端列表
//遍历这个列表,将消息发送给每个客户端
/* Send to clients listening for that channel */
de = dictFind(server.pubsub_channels,channel);
if (de) {
list *list = dictGetVal(de);
listNode *ln;
listIter li; listRewind(list,&li);
while ((ln = listNext(&li)) != NULL) {
redisClient *c = ln->value; addReply(c,shared.mbulkhdr[3]);
addReply(c,shared.messagebulk);
addReplyBulk(c,channel);
addReplyBulk(c,message);
receivers++;
}
}
/* Send to clients listening to matching channels */
发送到模式匹配的订阅方的处理... return receivers;
} //最后看看unsubscribe的处理:
void unsubscribeCommand(redisClient *c) {
if (c->argc == 1) {
//取消这个客户端的所有订阅
pubsubUnsubscribeAllChannels(c,1);
} else {
int j; for (j = 1; j < c->argc; j++)
//取消这个客户端的关于某个channel的订阅
pubsubUnsubscribeChannel(c,c->argv[j],1);
}
}
/* Unsubscribe from all the channels. Return the number of channels the
* client was subscribed from. */
int pubsubUnsubscribeAllChannels(redisClient *c, int notify) {
//取得这个客户端的所有订阅的channel的迭代器
dictIterator *di =dictGetSafeIterator(c->pubsub_channels);
dictEntry *de;
int count = 0;
//通过遍历迭代器来获取在客户端记录的每个channel记录,并对每个记录取消订阅
while((de = dictNext(di)) != NULL) {
robj *channel = dictGetKey(de); count +=pubsubUnsubscribeChannel(c,channel,notify);
}
/* We were subscribed to nothing? Still reply to the client.*/
if (notify && count == 0) {
addReply(c,shared.mbulkhdr[3]);
addReply(c,shared.unsubscribebulk);
addReply(c,shared.nullbulk);
addReplyLongLong(c,dictSize(c->pubsub_channels)+
listLength(c->pubsub_patterns));
}
dictReleaseIterator(di);
return count;
} * Unsubscribe a client from a channel. Returns 1 if the operationsucceeded, or
* 0 if the client was not subscribed to the specified channel. */
int pubsubUnsubscribeChannel(redisClient *c, robj *channel, int notify) {
struct dictEntry *de;
list *clients;
listNode *ln;
int retval = 0; //从客户端记录的hash表中删除这个channel记录,以此来取消客户对这个channel的订阅
//从服务端查找channel所对应客户端列表,从这个列表中删除这个客户端的记录
//这样就完成了取消订阅
/* Remove the channel from the client -> channels hashtable */
incrRefCount(channel); /* channel may be just a pointer tothe same object
we have in the hash tables. Protect it... */
if (dictDelete(c->pubsub_channels,channel) == DICT_OK) {
retval = 1;
/* Remove the client from the channel ->clients list hash table */
de = dictFind(server.pubsub_channels,channel);
redisAssertWithInfo(c,NULL,de != NULL);
clients = dictGetVal(de);
ln = listSearchKey(clients,c);
redisAssertWithInfo(c,NULL,ln != NULL);
listDelNode(clients,ln);
if (listLength(clients) == 0) {
/* Free the list and associatedhash entry at all if this was
* the latest client, sothat it will be possible to abuse
* Redis PUBSUB creatingmillions of channels. */
dictDelete(server.pubsub_channels,channel);
}
}
/* Notify the client */
if (notify) {
addReply(c,shared.mbulkhdr[3]);
addReply(c,shared.unsubscribebulk);
addReplyBulk(c,channel);
addReplyLongLong(c,dictSize(c->pubsub_channels)+
listLength(c->pubsub_patterns)); }
decrRefCount(channel); /* it is finally safe to release it*/
return retval;
}

redis-2.6.16源码分析之pub-sub系统的更多相关文章

  1. 鸿蒙内核源码分析(中断切换篇) | 系统因中断活力四射 | 百篇博客分析OpenHarmony源码 | v42.02

    百篇博客系列篇.本篇为: v42.xx 鸿蒙内核源码分析(中断切换篇) | 系统因中断活力四射 | 51.c.h .o 硬件架构相关篇为: v22.xx 鸿蒙内核源码分析(汇编基础篇) | CPU在哪 ...

  2. Redis学习——ae事件处理源码分析

    0. 前言 Redis在封装事件的处理采用了Reactor模式,添加了定时事件的处理.Redis处理事件是单进程单线程的,而经典Reator模式对事件是串行处理的.即如果有一个事件阻塞过久的话会导致整 ...

  3. 【Redis】事件驱动框架源码分析

    aeEventLoop初始化 在server.c文件的initServer函数中,对aeEventLoop进行了初始化: 调用aeCreateEventLoop函数创建aeEventLoop结构体,对 ...

  4. 【Redis】事件驱动框架源码分析(单线程)

    aeEventLoop初始化 在server.c文件的initServer函数中,对aeEventLoop进行了初始化: 调用aeCreateEventLoop函数创建aeEventLoop结构体,对 ...

  5. Android源码分析(三)-----系统框架设计思想

    一 : 术在内而道在外 Android系统的精髓在源码之外,而不在源码之内,代码只是一种实现人类思想的工具,仅此而已...... 近来发现很多关于Android文章都是以源码的方向入手分析Androi ...

  6. [Abp vNext 源码分析] - 23. 二进制大对象系统(BLOB)

    一.简介 ABP vNext 在 v 2.9.x 版本当中添加了 BLOB 系统,主要用于存储大型二进制文件.ABP 抽象了一套通用的 BLOB 体系,开发人员在存储或读取二进制文件时,可以忽略具体实 ...

  7. JNI-从jvm源码分析Thread.interrupt的系统级别线程打断原理

    前言 在java编程中,我们经常会调用Thread.sleep()方法使得线程停止运行一段时间,而Thread类中也提供了interrupt方法供我们去主动打断一个线程.那么线程挂起和打断的本质究竟是 ...

  8. 【Redis】事件驱动框架源码分析(多线程)

    IO线程初始化 Redis在6.0版本中引入了多线程,提高IO请求处理效率. 在Redis Server启动函数main(server.c文件)中初始化服务之后,又调用了InitServerLast函 ...

  9. 认识 Redis client-output-buffer-limit 参数与源码分析

    概述 Redis 的 client-output-buffer-limit 可以用来强制断开无法足够快从 redis 服务器端读取数据的客户端.保护机制规则如下: [hard limit] 大小限制, ...

  10. Redis学习之SDS源码分析

    一.SDS的简单介绍 SDS:简单动态字符串(simple dynamic string) 1)SDS是Redis默认的字符表示,比如包含字符串值的键值对都是在底层由SDS实现的 2)SDS用来保存数 ...

随机推荐

  1. (转)php中global和$GLOBALS[]的分析之一

    PHP 的全局变量和 C 语言有一点点不同,在 C 语言中,全局变量在函数中自动生效,除非被局部变量覆盖     这可能引起一些问题,有些人可能漫不经心的改变一个全局变量.PHP 中全局变量在函数中使 ...

  2. SQL后台分页三种方案和分析

    建立表:CREATE TABLE [TestTable] ( [ID] [int] IDENTITY (1, 1) NOT NULL , [FirstName] [nvarchar] (100) CO ...

  3. 【转】 iOS开发 剖析网易新闻标签栏视图切换(addChildViewController属性介绍)

    原文:http://blog.csdn.net/hmt20130412/article/details/34523235 本来只是打算介绍一下addChildViewController这个方法的,正 ...

  4. Swift 提示 error running playground...

    创建playground之后,我们将得到一个错误提示,Error running playground: Failed to prepare for communication with playgr ...

  5. 将对象保存至文件——CArchive

    CArchive允许以一个二进制的形式保存一个对象的复杂网络,也可以再次装载它们,在内存中重新构造,这一过程叫作串行化/序列化(Serialization),简单的说,CArchive与CFile配合 ...

  6. Oracle 体系结构及安全管理

    1 oracle数据库服务器构成:数据库和实例2 oracle内部结构: 物理存储结构: 数据文件(xxx.dbf):存放数据 控制文件(xxx.ctl):控制数据库的完整性恢复数据或使用的日志文件 ...

  7. ES5数组方法

    先标明参考出处: http://blog.csdn.net/codebistu/article/details/8049705 本来写过一篇有关数组新方法的(详见: [转]JavaScript函数和数 ...

  8. git log友好显示

    查看commit 提交日志 $ git log $git log --pretty=oneline $git reflog 显示所有提交记录,包括已经回退的提交,如图:提交了abc 和 bb 然后回退 ...

  9. JS中 confirm()方法的使用?

    confirm() 方法用于显示一个带有指定消息和 OK 及取消按钮的对话框. 如果用户点击确定按钮,则 confirm() 返回 true.如果点击取消按钮,则 confirm() 返回 false ...

  10. Delphi-Concat 函数

    函数名称 Concat 所在单元 System 函数原型 function Concat ( const String1 {,String2 ...} : string ) : string; 函数功 ...