C # Stackexchange.redis Simple to use

Source: Internet
Author: User
Tags redis server

Installing Stackexchange.redis

Search for Stackexchange.redis and Newtonsoft.json in NuGet and click on the button to install it directly.

Stackexchange.redis is a client of C # operations Redis database.

The Newtonsoft.json is used to serialize the JOSN string and to get the object deserialized.

References and initialization

Reference

using Stackexchange.redis; using Newtonsoft.json;

Initializing Redis

Connectionmultiplexer _conn = redisconnectionhelp.instance; // Initialize var database = _conn. Getdatabase (0); // Specify a connected library 0
String (String)

String is the most common type of data, and normal Key/value storage can be categorized as such.

A Key corresponding to a value,string type is binary safe. A Redis string can contain any data, such as a JPG image (which generates binary) or a serialized object.

Database. Stringset ("name"" cang "); // Set Stringset (key, value) string str = database. Stringget ("name"); // Result: Cang database. Stringset ("Name_two", str, timespan.fromseconds (ten)); // set the time to expire after 10s. 

Save object (object needs to be serialized into a string and then stored in the library)

Fetching Objects (deserialization)

//Create a pairElephantDemo Demo =NewDemo () {Name="Cang", Age= -, Height=1.83};stringDemojson = Jsonconvert.serializeobject (demo);//Serialization ofDatabase. Stringset ("Model", Demojson);stringModel = database. Stringget ("Model");d Emo= jsonconvert.deserializeobject<demo> (model);//deserialization

Stringincrement Increment, stringdecrement decrement (the default value is the same as 1)

Doubleincrement =0;DoubleDecrement =0; for(inti =0; I <3; i++) {Increment= database. Stringincrement ("stringincrement",2);//increments, +2 per time} for(inti =0; I <3; i++) {Decrement= database. Stringdecrement ("stringincrement");//Decrement, 1 per time}
List (lists)

The Redis list is a simple list of strings, sorted by insertion order. You can add an element to the head or tail of the list.

A list can contain up to 232-1 elements (4294967295, more than 4 billion elements per list).

 for(inti =0; I <Ten; i++) {database. Listrightpush ("List", i);//Enqueue, FIFO, here is the data inserted from the bottom} for(inti =Ten; I < -; i++) {database. Listleftpush ("List", i);//into the stack, advanced back out, here is the data from the top of the insert}varLength = database. Listlength ("List");//lengthvarRightpop = database. Listrightpop ("List");//Out of the team here is the data taken from the bottom

varLeftpop = database. Listleftpop ("List");//out of the stack, here is the data from the top of the

varList = database. ListRange ("List");

Hash (hashed)

Redis Hash is a string-type field and value mapping table, and hash is particularly useful for storing objects. Relative to Gencun each word of an object into a single string type. An object stored in a hash type consumes less memory and makes it easier to access the entire object.

Each hash in Redis can store 232-1 key-value pairs (more than 4 billion).

Hash of the store, give me the feeling similar to the relational database. In the example below, store a user object ( the table name in the relational database ), Cang, Shan, Yun (the primary key and unique value of the data in the relational database ), JSON ( field )

stringJSON = Jsonconvert.serializeobject (demo);//Serialization ofDatabase. HashSet ("User","Cang", JSON);d atabase. HashSet ("User","Shan", JSON);d atabase. HashSet ("User","Yun", JSON);
//Get model stringHashcang = database. Hashget ("User","Cang");d Emo= Jsonconvert.deserializeobject<demo> (Hashcang);//deserialization//Get listRedisvalue[] values = database. Hashvalues ("User");//Get all valueIlist<demo> demolist =NewList<demo>();foreach(varIteminchvalues) {Demo Hashmodel= jsonconvert.deserializeobject<demo>(item); Demolist. ADD (Hashmodel);}
Publish a subscription

Redis Publish Subscription (PUB/SUB) is a message communication pattern that can be used for the transmission of messages, and Redis's publish-subscribe mechanism consists of three parts, publishers, Subscribers, and Channel. Suitable for online chat, message push and so on.

Both the Publisher and the Subscriber are Redis clients, the channel is the Redis server side, the publisher sends the message to a channel, subscribers to the channel receive the message, and the client can subscribe to any number of channels.

Isubscriber Sub =_conn. Getsubscriber ();//Subscribe to CHANNEL1 channelSub. Subscribe ("Channel1",NewAction<redischannel, redisvalue> (channel, message) ={Console.WriteLine ("Channel1"+"Subscribe to receive message:"+( message);})); for(inti =0; I <Ten; i++) {Sub. Publish ("Channel1","msg"+ i);//send messages to channel Channel1    if(i = =2) {Sub. Unsubscribe ("Channel1");//Cancel Subscription    }}

because i = = 2 when the unsubscribe, so received a subscription message only 3.

Transaction

When a thing is turned on, the command action is encapsulated as a request sent to Redis to execute when the Execute method is called.

Here, you create a thing by using the CreateTransaction function (multi) and call its Execute function (EXEC) to commit the thing.

The "Condition.stringequal" ("Name", "name") is equivalent to the watch name in the Redis command.

stringName = database. Stringget ("name");stringAge = Database. Stringget (" Age");varTran = database. CreateTransaction ();//Create thingsTran. Addcondition (Condition.stringequal ("name", name));//optimistic LockTran. Stringsetasync ("name","Sea"); Tran. Stringsetasync (" Age", -);d atabase. Stringset ("name","Cang");//changing the name value at this time will fail when committing the thing. BOOLCommitted = Tran. Execute ();//Commit The thing, true succeeds, false rollback. 

Because the name value was modified in the process of committing the thing, the rollback was caused, and all the values of the name were assigned to the sea, and the age assignment of 25 failed.

Batch Batch Operations

Batch packages the required commands into a single request to Redis, and then waits for the results to be returned together. Reduce network overhead.

varBatch =database. Createbatch ();//Bulk WriteTask T1 = batch. Stringsetasync ("name","Feather"); Task T2= Batch. Stringsetasync (" Age", A); batch. Execute (); Task.waitall (t1, T2); Console.WriteLine ("Age :"+ database. Stringget (" Age")); Console.WriteLine ("Name:"+ database. Stringget ("name")); //Bulk Write for(inti =0; I <100000; i++) {batch. Stringsetasync (" Age"+I, i);} Batch. Execute ();//Bulk ReadList<task<redisvalue>> valueList =NewList<task<redisvalue>>(); for(inti =0; I <10000; i++) {Task<RedisValue> tres = batch. Stringgetasync (" Age"+i); Valuelist.add (tres);} Batch. Execute ();foreach(varRedisvalueinchvalueList) {stringvalue = Redisvalue.result;//remove the corresponding value value}
Lock (Distributed Lock)

Because Redis is a single-threaded model, commands operate atomically, so it is easy to implement distributed locks with this feature.

Redisvalue token =Environment.MachineName;//Lock_key represents the name of the lock in the Redis database and cannot be duplicated.
Token is used to identify who owns the lock and is used to release the lock.
A timespan indicates the effective time of the lock. Automatically released after 10 seconds to avoid deadlocks. if(Database. Locktake ("Lock_key", token, Timespan.fromseconds (Ten))){Try { //TODO: Start doing the things you needThread.Sleep ( the); } finally{database. Lockrelease ("Lock_key", token);//Release Lock }}
Stackexchange.redis Package

Link: https://pan.baidu.com/s/1rT9z567MVtfzQtnvdUxffw Password: 5k1b

Environment: VS2013 +. NET Framework 4.5

C # Stackexchange.redis Simple to use

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.