Stackexchange.redis Official document (i) "Basic usage"

Source: Internet
Author: User
Tags naming convention redis
Basic Usage

The connectionmultiplexer class is the central object of Stackexchange.redis, which is in the Stackexchange.redis namespace;
This object encapsulates the details of many of the underlying service objects. Because connectionmultiplexer does a lot of the underlying processing, it is designed to be shared and reused among callers. You should not create a connectionmultiplexer object for each operation. The object is fully thread-safe. In all subsequent examples,Connectionmultiplexer is assumed to be an object that is stored and reusable.
Now, let's create a. We can use Connectionmultiplexer.connect or Connectionmultiplexer.connectasync and pass a configuration string or Configurationoptions object to complete the creation. The configuration string can be separated by commas into a series of nodes, allowing us to connect to an instance using the default port 6379 on the local machine.

Using Stackexchange.redis;
...
Connectionmultiplexer Redis = Connectionmultiplexer.connect ("localhost");
^^ ^ Store and reuse the object

Note:connectionmultiplexer implements the IDisposable interface, and we can release it when it is not needed. However, I deliberately do not display the use using statement. Because the object is a resource-intensive object, it is best to reuse the object.

A more complex scenario may involve the setting of the master/slave service. For this usage, simply set a connection string that contains the master-slave server. (It can automatically identify the primary server)

Connectionmultiplexer Redis = Connectionmultiplexer.connect ("server1:6379,server2:6379");

If two nodes are found to be primary (primary), it is possible to resolve this problem by breaking the balance (tradeoff decision) by specifying that it is the primary server. But this is a very rare situation.

If you have a connectionmultiplexer object, then there are 3 things you might want to do: Access the Redis database (note: In the case of a cluster, a single logical database may be distributed across multiple nodes) using Redis's Publish/ Subscription functionality for maintenance and monitoring purposes, access to a standalone server using the Redis database

Accessing the Redis database is as simple as this:

Idatabase db = Redis. Getdatabase ();

The object returned by the Getdatabase method is a cheap pass-through object that does not require storage. Note that Redis supports multiple databases (although this is not a support cluster), and you can arbitrarily specify which database to invoke when calling Getdatabase . Also, if you plan to use asynchronous APIs, you need to specify a value for Task.asyncstate, or you can specify:

int databasenumber = ...
Object asyncstate = ...
Idatabase db = Redis. Getdatabase (Databasenumber, asyncstate);

Once you have the idatabase object, we can simply invoke the Redis API. Note that all methods have synchronous and asynchronous implementations. This is in line with Microsoft's naming convention, where async methods all end in Async and are all waiting.

The simplest operation is to store and retrieve a value:

String value = "ABCDEFG";
Db. Stringset ("MyKey", value);
...
String value = db. Stringget ("MyKey");
Console.WriteLine (value); Writes: "ABCDEFG"

Note The string prefix represents the string type of Redis, and it is associated with the. The sting type of net is very different to a large extent. Although both can store text data.
However, Redis allows both key and value to be native byte data. Examples are as follows:

byte[] key = ..., value = ...;
Db. Stringset (key, value);
...
Byte[] Value = db. Stringget (key);

The Redis data types that are covered by the Redis database commands are available. using the Redis Publish/Subscribe feature

Another common feature of Redis is as a distribution tool for publish/subscribe messages;
When the connection fails,Connectionmultiplexer will handle all the re-subscription details.

Isubscriber sub = Redis. Getsubscriber ();

getsubscriber Returns a cheap object that does not need to be stored. The Publish/Subscribe API does not have a database concept, but as mentioned earlier, we can provide an asynchronous state (Async-state). Note: All subscriptions are global. They are not confined to the isubscriber life cycle. The Publish subscription function is called the channel "channels" in Redis, and the channel does not need to be pre-defined on the server (an interesting use is the notification channel for each user, for example, the Stack Overflow real-time driver update section). This is. NET is common in that subscriptions use anonymous function callbacks to handle publishing messages:

Sub. Subscribe ("Messages", (channel, message) = = {
    Console.WriteLine (string) (message);
});

You can publish a message to the channel individually:

Sub. Publish ("Messages", "Hello");

This publishes "Hello" (real-time) to the console that subscribes to the message. As mentioned earlier, the byte type can be used for both the channel name and the message.

For sequential and message concurrency, refer to publish/Subscribe message sequence access to stand-alone servers

For maintenance purposes, it is sometimes necessary to issue a command specific to a server:

IServer Server = Redis. Getserver ("localhost", 6379);

The getserver method will accept a key-value pair object that is uniquely identified by a EndPoint object or server side. As before, theGetserver method returns a cheap object that does not need to be stored. Also the asynchronous state (async-state) is selectable to be specified. Note: The collection of available endpoints is also available:

endpoint[] Endpoints = Redis. Getendpoints ();

Server-side commands from IServer are available, for example:

DateTime lastsave = server. Lastsave ();
clientinfo[] Clients = server. Clientlist ();
Synchronous vs Asynchronous vs Instant Discard

In Stackexchange.redis, there are 3 main use mechanisms:

Synchronous-The method is returned to the caller before the operation is completed (note: Although this may block the caller, it will never block other threads; The key idea of Stackexchange.redis is that it actively shares connections between concurrent callers)

Asynchronous-the operation will be completed at some time in the future, with Task or task\

String value = "ABCDEFG";
Await DB. Stringsetasync ("MyKey", value);
...
String value = Await db. Stringgetasync ("MyKey");
Console.WriteLine (value); Writes: "ABCDEFG"

In all of the methods, the use of outgoing-to-discard access is accomplished with the optional parameter commandflags flags (which is passed in by default). When this is used, the method returns the default value immediately (so a method that usually returns a string will always return null, and returning a Int64 method will always return 0). The operation will continue to execute in the background. A typical use case is page click-through statistics:

Db. Stringincrement (Pagekey, flags:CommandFlags.FireAndForget);
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.