redis代码 发布订阅

struct redisServer {
    ...
    
    /* Pubsub */
    dict *pubsub_channels;  /* Map channels to list of subscribed clients */存放<channel, list> list中是订阅该pattern的client列表
    list *pubsub_patterns;  /* A list of pubsub_patterns */存放所有已订阅的pubsubPattern结构体
...
};

typedef struct redisClient {
    ...    
    dict *pubsub_channels;  /* channels a client is interested in (SUBSCRIBE) */存放该client定语的<channel, list> list是空。
    list *pubsub_patterns;  /* patterns a client is interested in (SUBSCRIBE) */存放该client订阅的pattern;robj类型。
    ...
} redisClient;


typedef struct pubsubPattern {
    redisClient *client;
    robj *pattern;
} pubsubPattern;

pubsubSubscribeChannel(redisClient *c, robj *channel):该client订阅该channel。
如果此前没订阅过, 则在redisClient::pubsub_channels中增加该channel、 同时在server::pubsub_channels的中增加该channel与client的相关信息
pubsubUnsubscribeChannel, pubsubSubscribeChannel的逆过程。

pubsubSubscribePattern与channel类似,只不过是用list维护的<client, pattern>
pubsubUnsubscribePattern, pubsubSubscribePattern的逆过程。

pubsubPublishMessage(robj *channel, robj *message) 发布消息: 从server::pubsub_channels中找到该channel下的所有client,发消息。 
并从server::pubsub_patterns下逐个检查pattern是否匹配该channel, 匹配则给该client发消息。

pattern使用list, channel使用dict, 是由于pattern可能是正则式,list顺序遍历简单、dict无必要。

取消过程中, 如果无订阅了则删除相关的pattern或者channel。




你可能感兴趣的:(redis代码 发布订阅)