Redis is a fast, stable publish/subscribe information system.
Here are the relevant introduction
You can use this publish subscription system to implement chat functions.
1, suppose there are two users, User1 and User2, each creating a Redis connection.
u1 = Redis.new
U2 = Redis.new
2,U1 Subscribe to a channel Channel1
" Channel1 " do |on| |channel, subscriptions| "Subscribed to##{channel} (#{subscriptions} subscriptions)" End |channel, msg| "#{channel}: #{msg}" EndEnd
U1 Enter the listening wait state
# subscribed to #channel1 (1 subscriptions)
3,U2 Publishing a message
' Channel1 ' ' Hello '
4,U1 receive new messages and print them out
# subscribed to #channel1 (1 subscriptions) # Channel1:hello
5,block block, there are three types of callbacks, the first 2 have been seen, subscribe and message, the third is unsubscribe.
Redis.subscribe (: One,:) do |on|#Channel : Current channel, subscriptions: number of channelsOn.subscribe do |channel, subscriptions|puts"subscribed to ##{channel} (#{subscriptions} subscriptions)"End#Channel : Current channel, message: ContentOn.message do |channel, message|puts"##{channel}: #{message}"Redis.unsubscribeifMessage = ="Exit"End#On.unsubscribe do |channel, subscriptions|puts"unsubscribed from ##{channel} (#{subscriptions} subscriptions)"End End
PS: code from HTTPS://GITHUB.COM/REDIS/REDIS-RB/BLOB/MASTER/EXAMPLES/PUBSUB.RB
You can define various rules in the message to implement the management of the channel.
6, here are some methods related to publishing and subscribing.
Psubscribe. Subscribes to the given pattern.
Redis.psubscribe ('c*') Do |on|On.psubscribe Do|channel, subscriptions|puts"subscribed to ##{channel} (#{subscriptions} subscriptions)"End On.pmessage do|pattern, Channel, message|puts"##{channel}: #{message}"Redis.unsubscribeifMessage = ="Exit"End On.punsubscribe do|channel, subscriptions|puts"unsubscribed from ##{channel} (#{subscriptions} subscriptions)"End End
The difference with subscribe is that the parameter is a matching pattern, and the three methods in the block also correspond to the changes.
Summary: This focuses on the usage examples of publishing and subscription related in Redis. One user can subscribe to multiple channels, or they can post messages to multiple channels.
Redis Ruby Client Learning (iv)