Redis's publish-subscribe model

Source: Internet
Author: User
Tags rehash sub command redis server

OverviewEach Redis server instance maintains a redisserver structure that holds the server state, struct redisserver{/*/Pubsub///dictionary, key to channel, value to list//list of all clients subscribed to a channel  The new client is always added to the footer of the list dict *pubsub_channels;  /* MAP channels to List of subscribed clients *///////This list records the names of all the modes that the client subscribes to the list *pubsub_patterns; /* A list of Pubsub_patterns */};p Ubsub_channels records information about the channels subscribed to by all clients. Redis's publish-subscribe model

Subscribers subscribe to the channel via the Sub command, and the server pushes the message to the eligible Pubsub_channels using the Pub command.

internal data StructurePubsub_channels is a dictionary structure that uses hash tables to store and index data inside a dictionary. An optional data structure that implements a dictionary Hash Table: Simple but unstable array-based conflict resolution method; Simple and average efficient and stable chain address conflict resolution; Dictionary Tree: Use the tree structure. Redis uses the hash chain address method as the realization, the benefit is intuitive, simple, can expect the average time complexity is small and smooth. typedef struct dict {    //  type-specific function     dicttype  *type;    //  Private Data     void *privdata;     //  Hash Tables     dictht ht[2];    // rehash  Indexes     //  when  rehash  is not in progress, the value is  -1    int rehashidx;  /* rehashing not in progress if rehashidx == -1 */     //  number of security iterators that are currently running     int iterators; /* number  Of iterators currently running */} dict;dict uses two hash tables for indexing, and when rehash is used, the hash table of ht[1] All other times use the hd[0] hash table. The hash table used is defined as follows typedef struct dictht {    //  hashtable array      dictEntry **table;    //  Hash TableSize     unsigned long size;    //  Hash Table size mask, used to calculate index values      //  always equals  size - 1    unsigned long sizemask ;    //  The hash table already has the number of nodes     unsigned long used;}  dictht;table is an array of dictentry* pointers, and each item in the table is a pointer to the DICTENTRY structure, and each item has a pointer to the next item. It can be seen that this is a hash structure that uses the chain address method to resolve conflicts. The definition of Dictentry, which contains key, value, next. /* *  Hash table nodes  */typedef struct dictEntry {    //  keys      void *key;    //  Values     union {         void *val;         uint64_t u64;        int64_t s64;    }  v;    //  point to the next hash table node, forming the linked list     struct dictentry *next;}  dictEntry; client subscription channel is the process of inserting a new element in the dictionary        //  Association         // {         //   Channel name          Subscribe to channel clients         //   ' Channel-a '  : [c1, c2,  c3],        //   ' Channel-b '  : [c5, c2,  c1],        //   ' Channel-c '  : [c10, c2,  c1]        // }         /* add the client to the channel -> list of clients  hash table */        //  from  pubsub_channels The   dictionary takes out the linked list of all the clients that have subscribed to  channel ,         //  if   channel  does not exist in the dictionary, then add in         de = dictfind (Server.pubsub_channels,channel) ;        if  (de == null)  {             clients = listcreate ();             dictadd (server.pubsub_channels,channel,clients);             incrrefcount (channel);         } else {             clients = dictgetval (DE);        }         // before:        //  ' channel '  : [c1, c2]        // after:         //  ' channel '  : [c1, c2, c3]        //  Add the client to the end of the list         listaddnodetail (clients,c); 1. Queries whether server contains the specified channel 2. If the channel exists, get the list address that the channel points to, and if the channel does not exist, create channels and LIST3. Use the list in step 2 to add the client to the end of the list. After completing these three steps, the server maintains a subscription channel with a new channel and a client of interest, which detects the publication subscription dictionary when the server publishes, obtains the subscription client and sends it sequentially.server release message to channel /* send to clients listening for that channel */     //  Remove the list of clients that contain all subscribed channels  channel      //  and send messages to them      de = dictfind (Server.pubsub_channels,channel);    if  (DE)  {         list *list = dictgetval (DE);         listNode *ln;        listIter  li;        //  traverse the list of clients and send  message  to them          listrewind (List,&li);         while   ((Ln = listnext (&li))  != null)  {             redisClient *c = ln->value;             //  reply to the client.             //  Example:             // 1)   "message"              // 2)   "XXX"              // 3)   "Hello"              addreply (c,shared.mbulkhdr[3]);             //  "message"   string              Addreply (c,shared.messagebulk);             // Source channel for   messages             addreplybulk (C,channel);             //  Message Content       &nbsP;      addreplybulk (c,message);             //  Receive client Count              RECEIVERS++;        }   &NBSP the process of subscribing to a subscriber, The publishing process is a process for finding subscribers and polling for sending messages to subscribers.

Publish subscription mode for Redis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.