Servicestack.redis's iredisclient 03_ turn

Source: Internet
Author: User
Tags redis server

In fact, many of the methods in Iredisclient are actually the name of the Redis command. As long as you are familiar with Redis commands, you can understand these methods very quickly, and while you are not particularly knowledgeable about Redis, I am also looking at these methods with commands.

First, the attribute

The properties of the Iredisclient are as follows:

Property Description
ConnectTimeout Connection timed out
Db ID or subscript of the current database
Dbsize The number of keys in the current database
Hadexceptions
Hashes Stores complex objects, a value that has several field
Host Server server host address for Redis
Info Returns various information and statistics about the Redis server
Lastsave The last time Redis successfully saved data to disk
Lists All list collections in the current database
Password Password
Port Server ports for Redis
RetryCount Retry Count
Retrytimeout Retry timeout
Sendtimeout Send Timeout
Sets All hashset<t> collections in the current database
Sortedsets All sortedset<t> collections in the current database
This[string Key] Accessing a String type value by means of an index (key)

code example:

  
Rclient.additemtoset ("Shu", "Liu Bei");        Rclient.additemtoset ("Shu", "Guan Yu");        Rclient.additemtoset ("Shu", "Zhang Fei");        Ihasnamed<iredisset> rr = rclient.sets;        hashset<string> hashsetstring = rr["Shu"]. GetAll ();        foreach (String str in hashsetstring)        {            Response.Write (str);        }

Second, iredisclient data operation

  1. Icacheclient interface

Iredisclient implements the interface Icacheclient, where icacheclient mainly provides the following functions:

Method Description
Add Adds a record based on the incoming Key-value, and returns False when key already exists
Flushall Invalidates all caches (clears all keys for all Redis databases)
Get Gets the value of a record based on the key passed in
GetAll Get values for multiple records based on multiple keys passed in
Remove Removes a record based on the key passed in
RemoveAll Remove multiple records based on multiple keys passed in
Replace Overwrites the value of a record according to the key passed in, and does not add when key does not exist
Set Modifies the value of a record according to the key passed in, and adds if the key does not exist
SetAll Overwrite multiple records based on the number of keys passed in
Increment
Decrement

Specifically, for example, the main method of adding includes two overloads, one more datetime type parameter, and one more timespan type parameter. Both are the time the cache expires (equivalent to the absolute expiration time in the cache dependency).

    • DateTime failure point: arrives at that point in time , immediately fails;
    • TimeSpan failure point: after that time period, the immediate failure;

Simple example:

  
Public ActionResult Index ()        {            Redisclientmanagerconfig redisconfig = new Redisclientmanagerconfig ();            Redisconfig.autostart = true;            Redisconfig.maxreadpoolsize =;            Redisconfig.maxwritepoolsize =;            Pooledredisclientmanager PRCM = new Pooledredisclientmanager (new list<string> () {"127.0.0.1"}, New list< String> () {"127.0.0.1"}, Redisconfig);            using (iredisclient rclient = prcm. Getclient ())            {                Rclient.add ("C1", "Cache 1");                Rclient.set ("C1", "Cache 2");                Rclient.replace ("C1", "Cache 3");                Response.Write (rclient.get<string> ("C1"));                Rclient.remove ("C1");                Response.Write (rclient.get<string> ("c1") = = null);            }            Return Content ("");        }

  2. Simple function

Of course, in addition to the function of implementing the Icacheclient interface, there are actually many functions for basic operation.

Method Description
Appendtovalue Appends the parameter value to the end of the original value according to key
ContainsKey Determine if key has been used within this database (including various types, built-in collections, etc.)
Getallkeys Get all the Keys collection
Decrementvalue The value is reduced by 1 according to the specified key (only integer valid)
Decrementvalueby Subtracts a value from a specified value, based on the specified key (only integer valid)
Incrementvalue Adds a value of 1 to the specified key (only integer valid)
Incrementvalueby Adds a value to the specified value, based on the specified key (only integer valid)
Renamekey Rename a key, the value does not change
Searchkeys Find the collection of keys of equal name from the database, special mode such as H[ae]llo, only valid in English.
Getrandomkey Randomly get a key that has already been used
GetValue Gets a value based on key, only valid for string type
GetValues Gets multiple values based on multiple keys entered, supports generics
Gettimetolive Gets the timespan of the item of the specified key distance from the failure point
Getsortedsetcount Gets the number of items in the sorted collection, with parameters that support subscript and score filtering
Expireentryat Sets the expiry time (DateTime) of an item according to the specified key
Expireentryin Sets the expiry time (TimeSpan) of an item based on the specified key
Flushdb Erase all data from this database
Flushall Clears all data for all databases
Shutdown Stop all clients, save, and close the Redis service
Save Save data DB file to hard disk
Saveasync Asynchronous Save
Rewriteappendonlyfileasync Append data to server files only in asynchronous situations
Writeall
PublishMessage Sends a message to the specified channel
Storeobject
Getvaluesmap Returns multiple data of the same value type in key-value pairs, supporting generics and return strings.
String
Setentry Modifies a value according to key, which is overwritten by the presence. (Only strings can be set)
Setentryifnotexists Set a value based on key, which is valid only if key does not exist, as the key already exists and does not modify (only strings are supported)
Setentryifnotexists Sets a value based on key to return the old value.
Getentrytype

Gets the current stored value according to the key type:

None = 0
String = 1
List = 2
Set = 3
SortedSet = 4
Hash = 5

  

  

  3. Built-in collection

For example, Iredisclient supports the maintenance of data of the following collection types internally:

    • List<t>
    • Sorted list<t> (SortedSet after. Net 4.0)
    • Hashset<t>

Operations on the following 4 types of data:

Method Description
Additemtolist Add an item to the internal list<t>
Additemtoset Add an item to the internal hashset<t>
Additemtosortedset Adds an item to the internal sort list<t>, where the overloaded method has more than one score: the sorted value. Prioritize according to score from small to large, otherwise by value to big sort
Addrangetolist Add more than one value from a list<t> in a parameter to an internal list<t>
Addrangetoset Add more than one value from a hashset<t> in a parameter to an internal hashset<t>
Addrangetosortedset Adds more than one value from a list<t> in an argument to an internal list<t> at a time, and the score of an overloaded method represents a sorted value.
Getallitemsfromlist Gets all values for the internal list<t> of the specified Listid
Getallitemsfromset Gets all values for the internal hashset<t> of the specified SetID
Getallitemsfromsortedset Gets all values for the internally sorted list<t> of the specified Listid
Getallitemsfromsortedsetdesc Gets all values for the internally sorted list<t> of the specified Listid, but the obtained values are in reverse order.
Getrangefromlist Gets the data for the specified subscript range in the internal list<t> of the specified Listid
Getrangefromsortedlist Gets the data for the specified subscript range in the internally sorted list<t> of the specified Listid
Getrangefromsortedset Gets the data for the specified subscript range in the internal hashset<t> of the specified SetID
Getrangefromsortedsetbyhighestscore Gets the data in the internal hashset<t> of the specified SetID in accordance with the score of the high-and low-order values, and supports the skip, take
Getrangefromsortedsetbylowestscore Ibid., except that the data in a certain range is determined by the score score from low to high
Getrangefromsortedsetdesc Gets the data within the specified subscript range of the internal hashset<t> in reverse order
Getrangewithscoresfromsortedset Same as from, except for key-value pairs, with a score in the data score
Getrangewithscoresfromsortedsetbyhighestscore Ditto
Getrangewithscoresfromsortedsetbylowestscore Ditto
Getrangewithscoresfromsortedsetdesc Ditto
Getallwithscoresfromsortedset Gets the ordered internal list<t> of the specified Listid and its score
Getsorteditemsfromlist Gets a collection of the specified sort from the list<t> of the specified Listid, supporting Skip,take
Getsortedentryvalues Gets the item sorted by the specified starting position and number from the list<t> of the specified Listid
Removeallfromlist Removes the internal list<t> of the specified Listid
Removeitemfromlist Removes the equivalent of the second parameter value in the internal list<t> of a specified Listid
Removeitemfromset Removes the item equal to the second parameter value from the internal hashset<t> of the specified SetID
Removeitemfromsortedset Removes the item of equal value from the sorted internal list<t> in the specified Listid
Removerangefromsortedset Removes an item of the specified subscript range from the specified Listid sorted list<t>
Removerangefromsortedsetbyscore Removes an item of the specified score range from the specified Listid sorted list<t>
Removestartfromlist Removes the beginning item from the specified Listid
Removeendfromlist Removes the end item from the specified Listid
Blockingremovestartfromlist To remove from the specified listid the beginning of the block
Blockingremovestartfromlists
RemoveEntry Clears multiple internal list<t> based on multiple Listid passed in
Removeallluascripts Clear all Lua script caches
Removeentryfromhash
Getitemfromlist Get an item based on Listid and subscript
Getitemindexinsortedset Gets the subscript of the built-in sorted list<t> based on list and value
Getitemindexinsortedsetdesc Ditto, but in the opposite order
Getitemscoreinsortedset Gets the score of the built-in list<t> items based on the incoming Listid and values
GetListCount Gets the number of entries for the built-in list<t> according to Listid
Getsetcount Gets the number of entries for the built-in hashset<t> according to SetID
Getintersectfromsets Get the intersection from the IDs of multiple hashset<t> entered
Getunionfromsets Get the hashset<t> from the IDs of multiple inputs
Getrandomitemfromset Gets the random item from the collection of the specified Listid
Storeunionfromsets Combine multiple hashset<t>, and merge as a large hashset<t> in the first argument; the hashset<t> in the first argument may not exist
Storeunionfromsortedsets Combine multiple sortedset<t>, and merge as a large sortedset<t> in the first argument; the sortedset<t> in the first argument may not exist
Storeintersectfromsets The intersection result is saved in the first parameter's collection, and the hastset<t> effect
Storeintersectfromsortedsets The intersection result is saved in the first parameter's collection, and the sortedset<t> effect
Enqueueitemonlist Stores an element in the head of the list<t> of the specified Listid
Dequeueitemfromlist List<t> the element at the end of the specified Listid to return the dequeue element
Blockingdequeueitemfromlist Dequeue the element at the end of the list<t> that specifies Listid, except that it blocks the LIST<T>, supports a timeout, and returns a DEQUEUE element
Blockingdequeueitemfromlists
Blockingpopitemfromlist Blocks which element at the end of the list<t> of the specified Listid is removed
Blockingpopitemfromlists
Blockingpopandpushitembetweenlists Removes the element from the first collection and adds it to the head of the second collection, returning the element, blocking two sets at a time
Popitemfromlist Removes an item from the end of list<t> of the specified Listid and returns
Popitemfromset Removes an item from the end of hashset<t> of the specified SetID and returns
Popitemwithhighestscorefromsortedset Removes the score highest item from the hashset<t> of the specified SetID
Popitemwithlowestscorefromsortedset Removes the lowest score from the hashset<t> of the specified SetID
Popandpushitembetweenlists Removes the elements from the first collection and adds the header to the second collection
Setcontainsitem Determines whether the specified value is included in the hashset<t> for the specified SetID (string only)
Sortedsetcontainsitem Determine if SortedSet contains a key
Trimlist Trim the built-in collection according to Listid, preserving the elements between the from->at (containing the From
Incrementiteminsortedset The value score plus the specified score for the values in the specified Listid collection
Setiteminlist Re-sets the value of the specified Listid and subscript to the specified values
Pushitemtolist Into row a key-value pair in the built-in list<t> of the specified Listid, at the end
Prependitemtolist Inserts a value to the front of the list<t>
Prependrangetolist Add multiple values at once to the built-in list<t> of the specified Listid
Getdifferencesfromset Returns data that exists in the first collection, but does not exist in the other collection. Subtraction
Storedifferencesfromset Saves the result of the differential set in the collection of the first parameter
Movebetweensets Moves an element from one collection to the beginning of another collection. (Delete and add)

Here is an example of list<t> and hashset<t>:

Internal maintenance of a list<t> set        rclient.additemtolist ("Shu", "Liu Bei");        Rclient.additemtolist ("Shu", "Guan Yu");        Rclient.additemtolist ("Shu", "Zhang Fei");        list<string> liststring = rclient.getallitemsfromlist ("Shu");        foreach (String str in liststring)        {            Response.Write (str);    Output Liu Bei Guan yu Zhang                       rclient.additemtoset ("Wei", "Cao");        Rclient.additemtoset ("Wei", "Cao");        Rclient.additemtoset ("Wei", "Dian Wei");        hashset<string> hashsetstring = Rclient.getallitemsfromset ("Wei");        foreach (String str in hashsetstring)        {            Response.Write (str);    Output Code Vecao        }

Here is another example of the scope range operation:

        Internal maintenance of a list<t> set        rclient.additemtosortedset ("Shu", "Liu Bei", 5);        Rclient.additemtosortedset ("Shu", "Guan Yu", 2);        Rclient.additemtosortedset ("Shu", "Zhang Fei", 3);        idictionary<string,double> dicstring = Rclient.getrangewithscoresfromsortedset ("Shu", 0, 2);        foreach (Var r in dicstring)        {            Response.Write (R.key + ":" + r.value);    Output         }

3. Built-in hash

Internal maintenance a Hashtable

Method Description
Setentryinhash Sets a key-value pair into the hash table, overwriting if the key of the Hashtable is present
Setentryinhashifnotexists When a hash table key is not used, set a key value pair such as hash
Gethashvalues Get multiple values under Hashid based on the Hashid
Getvaluesfromhash Get multiple values based on the key of the Hashid and hash table (multiple keys supported)
Getvaluefromhash Get a single value based on the key of the Hashid and hash table
Gethashkeys Gets all keys under the specified Hashid
Gethashvalues Gets all values under the specified Hashid
Gethashcount Gets the number of all keys under the specified Hashid
Hashcontainsentry Determines whether the specified Hashid contains the specified key in the hash table
Incrementvalueinhash Adds the value from the hash table of the specified Hashid to the specified value
Storeashash Hash an object (supports generics)
Getfromhash Extract objects from the hash table by ID (supports generics)
Setrangeinhash by ienumerable<keyvaluepair<string, string>> sets multiple values at once, and when the internal hash key does not exist, it is added, and the presence is overwritten

code example:

        Rclient.setentryinhash ("xxx", "key", "123");        list<keyvaluepair<string, string>> keyvaluepairs = new list<keyvaluepair<string, string>> ();        keyvaluepair<string, string> kvp = new keyvaluepair<string, string> ("Key", "1");        Keyvaluepairs.add (KVP);        Rclient.setrangeinhash ("xxx", keyvaluepairs);

  

  4. Lua Script

Starting with the Redis 2.6.0 release, a variety of LUA scripts can be executed with the built-in LUA interpreter. Iredisclient supports the execution of LUA scripts, which are used to execute LUA scripts in the following ways:

Method Description
Loadluascript Loads a script into the script cache, but does not run it immediately
Killrunningluascript To stop a script that is running a specified ID
Execluaasint
Execluaaslist
Execluaasstring
Execluashaasint
Execluashaaslist
Execluashaasstring
Hasluascript Determine if the Lua script is in the script cache
CalculateSha1
Whichluascriptsexists

About the Lua script can be here to understand: http://www.cnblogs.com/ly4cn/archive/2006/08/04/467550.html

  5. Business

Transactions in Redis

Method Description
Watch Monitor one (or more) key, and if this (or these) key is changed by another command before the transaction executes, the transaction will be interrupted.
Unwatch Suppress watch command for all key monitoring
Acquirelock Apply to a key locking (during which other objects cannot be accessed)
CreateTransaction Creates a transaction that returns a Iredistransaction object
Createsubscription Creating a subscription event returns a Iredissubscription object
Createpipeline Returns a Iredispipeline object

Servicestack.redis's iredisclient 03_ turn

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.