C # StackExchange used by Redis,
Chapter 4 installation
To use Redis on the. NET platform, make the following preparations:
Create a New Visual Studio Application or open an existing Visual Studio Application.
Open the NuGet package
Search for and add a StackExchange. Redis package
Chapter 4 data cache
Use redis as a data cache service
String host = "192.168.200.131 ";
// Obtain the connection object
ConnectionMultiplexer redis = ConnectionMultiplexer. Connect (host );
// Obtain the database object
IDatabase db = redis. GetDatabase ();
// Set the Data Object
Db. StringSet ("User", "{Name: \" TOM \"}");
// Add a Data Object
Db. StringAppend ("User", ", {Name: \" JACK \"}");
// Obtain the data object
String user = db. StringGet ("User ");
Console. WriteLine (user );
Chapter 4 subscription and Publishing
Publish messages
Static void Main (string [] args)
{
String host = "192.168.28.106 ";
// Obtain the connection object
ConnectionMultiplexer redis = ConnectionMultiplexer. Connect (host );
// Set the Data Object
// Obtain the subscription object
ISubscriber sub = redis. GetSubscriber ();
// Publish a message to channel: c1
Sub. Publish ("c1", "123 ");
// Send a 1 million-character message
Sub. Publish ("c1", "zx". PadRight (1000000, 'x '));
String reader = "start send ";
While (reader! = "Exit ")
{
Reader = Console. ReadLine ();
Sub. Publish ("c1", reader );
}
Console. ReadLine ();
}
Subscribe to messages
Static void Main (string [] args)
{
String host = "192.168.28.106 ";
// Obtain the connection object
ConnectionMultiplexer redis = ConnectionMultiplexer. Connect (host );
// Set the Data Object
// Obtain the subscription object
ISubscriber sub = redis. GetSubscriber ();
// Set subscription events
Sub. Subscribe ("c1", new Action <RedisChannel, RedisValue> (GetMessage ));
Console. Read ();
Console. ReadLine ();
}
/// <Summary>
/// Obtain the message
/// </Summary>
/// <Param name = "channel"> </param>
/// <Param name = "message"> </param>
Static void GetMessage (RedisChannel channel, RedisValue message)
{
Console. WriteLine (channel );
Console. WriteLine (message );
}