Click here to Skip to main content
15,881,204 members
Articles / Programming Languages / Visual Basic
Article

Redis Tutorial Part II: Using Redis as a Pub/Sub Medium

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
2 May 2011CPOL2 min read 33.1K   10.6K   3  
Create a simple redis pub/sub client pair in VB.NET

Introduction

If you have gone through Part I of this series, you will now have a bit of an idea of what redis is and its simple but awesome power. This part explains how redis can act as a publish - subscribe medium. In simpler terms- Notifications: the simplest of things that makes coding so much easier! This series will conclude with Part III: Creating a chat system with Redis in VB.NET.

Background

As with its predecessor, this tutorial is going to be simple and direct. I can show you what powers you, not how to use them :D. One of the most powerful features of redis is its PubSub mode. In other words, when something happens, anything that wants to know it will be informed. This tutorial will show you the fundamental way to use this. My next tutorial will show how to develop a complete chat application (twitter/Facebook) in VB.NET. I know that mostly applications like that are developed in the web platform, but for the purpose of these tutorials, I am going to use it anyway.

Using the Code

The prerequisites are the same as from part I. You can use the same project or build a new one.

Here, we'll have a single application that can be run in 2 modes:

  1. As a Subscriber
  2. As a Publisher

I've built the project in such a way that this is toggled by a menu at startup. You may use it as different applications too! Run the EXE more than once to use it...

VB.NET
Imports ServiceStack.Redis

Public Class SubscriptionMessageEventArgs
    Inherits EventArgs

    Public Property Key As String
    Public Property value As String

    ''' <summary>
    ''' Initializes a new instance of the SubscriptionMessageEventArgs class.
    ''' </summary>
    Public Sub New(ByVal key As String, ByVal value As String)
        Me.Key = key
        Me.value = value
    End Sub
End Class

''' <summary>
''' The redis store encapsulation class around the ServiceStack redis client 
''' </summary>
''' <remarks>This class is cumulatively constructed 
''' across the tutorial and is not broken.
''' </remarks>
Public Class RedisStore

#Region " Properties "
     Private _sourceClient As RedisClient
    Public ReadOnly Property SourceClient() As RedisClient
        Get
            Return _sourceClient
        End Get
    End Property

#End Region

#Region " Event "
     Public Event OnSubscriptionMessage As EventHandler(Of SubscriptionMessageEventArgs)
#End Region

#Region " Constructors "
     Public Sub New()
        MyClass.New(False)
    End Sub

    Public Sub New(ByVal ForceCheckServer As Boolean)
        _sourceClient = New RedisClient
        If ForceCheckServer AndAlso Not IsServerAlive() Then
            Throw New Exception("The server has not been started!")
        End If
    End Sub

#End Region

    Public Function IsServerAlive() As Boolean
        Try
            Return SourceClient.Ping
        Catch ex As Exception
            Return False
        End Try
    End Function

#Region " Functionalities "
 #Region " Get/Set Keys "
     Public Function SetKey(ByVal key As String, ByVal value As String) As Boolean
        Return SourceClient.Set(key, value)
    End Function

    Public Function SetKey(Of T)(ByVal key As String, ByVal value As T) As Boolean
        Return SourceClient.Set(Of T)(key, value)
    End Function

    Public Function GetKey(ByVal key As String) As String
        Return Helper.GetString(SourceClient.Get(key))
    End Function

    Public Function GetKey(Of T)(ByVal key As String) As T
        Return SourceClient.Get(Of T)(key)
    End Function

#End Region

#Region " Pub/Sub "
     Public Sub Subscribe(ByVal ParamArray channels() As String)
        Dim SubClient As IRedisSubscription = SourceClient.CreateSubscription
        SubClient.OnMessage = New Action(Of String, String)(AddressOf OnMessage)
        SubClient.SubscribeToChannels(channels)
    End Sub

    Private Sub OnMessage(ByVal channel As String, ByVal value As String)
        RaiseEvent OnSubscriptionMessage_
	(Me, New SubscriptionMessageEventArgs(channel, value))
    End Sub

    Public Sub Publish(ByVal channel As String, ByVal value As String)
        SourceClient.Publish(channel, Helper.GetBytes(value))
    End Sub

#End Region

#End Region

End Class

Public Class Helper

    Private Shared ReadOnly UTF8EncObj As New System.Text.UTF8Encoding()

    Public Shared Function GetBytes(ByVal source As Object) As Byte()
        Return UTF8EncObj.GetBytes(source)
    End Function

    Public Shared Function GetString(ByVal sourceBytes As Byte()) As String
        Return UTF8EncObj.GetString(sourceBytes)
    End Function

End Class

To subscribe to an array of channels, call the Subscribe function. To publish to a channel, call the Publish function. As you may see, a client that subscribes cannot do anything else. We deal with this situation in the next tutorial, unless of course you figure out the simple solution for it on your own!

Well, that's it for the second part of the tutorial. Do ask and comment if you have any queries.

History

  • 1st May, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
India India
Hariharan leapt into the field of programming after being introduced to C in his second year at college. A fan of basketball and chess, the logical thought process behind programming and the concepts of linking real principles onto a concrete platform pushed him deep into this field. On finishing his bachelor's majoring in Electrical and Electronics engineering with Soft Computing, Numerical Analysis and Biomedical Engineering as minor, he did a six month stint at India's second largest IT company- Infosys Technologies. He left Infosys armed with strong concepts of SDL Cycles and process development, gained domain knowledge in Java and had explored Visual basic, C++, C# and kept his mind open for more. Currently working in a startup as the product designer, his arsenal of technologies has doubled to accommodate the challenges his job demands.
Off work, he enjoys learning new languages (non-programming) and is currently teaching himself German and Spanish. He also enjoys travelling around and exploring new ideas, places and relationships.

Currently attempting to extend his education to post graduation.

Comments and Discussions

 
-- There are no messages in this forum --