Basic Tutorials of Redis(7) -Publish and Subscribe

  This post is mainly about the publishment and subscription in Redis.I think you may subscribe some offiial

accounts on wechat,and when the authors published something new to their accounts,you will get them in

your wechat.The instance can make you understand this pattern easily.You will find there only 6 commands

for publishment and subscription.

   This post introduces the basic usages as well.I will show you how to publish a message to a channel.publish

is the command to publish sometings.I publish a channel named news-nba with the message nba.And the client

return me a integer 0.What is the meaning of the return value?It means that there is nobody subscribe this channel.

publish news-nba nba

   I open a new client for subscriber.In this client,I subscribe the above channel news-nba.It will return something

about this channel.

subscribe news-nba

   OK,let's publish a new message to the news-nba to see the changes in the both clients.After publishing lakers to

the news-nba channel,this client returns 1.It means that the channel has a subscriber.

publish news-nba lakers

   Let's turn to the subscriber's client.You will find the message lakers was already in the client.So amazing it is.

  

  Opening the second client to subscribe this channel,and you will find something similar with the above example.

  

   publish a new message to the news-nba,it returns 2 meaning ...(you understand it)

  

  the both subscribers' client are as follows:

  

  

   All right,let's see the other commands of this feature in Redis.Seeing the sql first:

  channels channelname  To execute this sql,you will get all of the channel whoes 

name start with news.Redis can also 

psubscribe news-*

  Let's publish some message to the others channel started with news- to find out the changes.
publish newstech tech

   The subscriber's client will receive the message from the channel news-tech.

   Again!!Publishing a message to a new channel.

   As you can see,the client receives this message as well.

following code demonstrates the usage in C#.

sub = sub2 = sub.Publish(, sub.Publish(, sub2.Subscribe(,(channel,value) => Console.WriteLine(.Format( sub2.Subscribe(,value) => Console.WriteLine(.Format( sub.Publish(, sub.Publish(, sub.Publish(, System.Threading.Thread.Sleep( Console.WriteLine( sub2.Unsubscribe(); sub.Publish(, System.Threading.Thread.Sleep( sub.Publish(, System.Threading.Thread.Sleep( Console.WriteLine( sub.Publish(, sub.Publish(,);
  Debuging the code,you will see the result as follow. 

  

  The next post of this series is the basic opreation of transaction in Redis.Thanks for your reading.

相关文章

在笔者近 3 年的 Java 一线开发经历中,尤其是一些移动端、用...
这一篇文章拖了有点久,虽然在项目中使用分布式锁的频率比较...
本文梳理总结了一些 Java 互联网项目中常见的 Redis 缓存应用...
书接上回,消息通知系统(notification-system)作为一个独立...
Redis 是目前互联网后端的热门中间件之一,在许多方面都有深...
在Java Spring 项目中,数据与远程数据库的频繁交互对服务器...