Redis applications in the. NET Architecture (1)--using Servicestack to connect Redis (GO)

Source: Internet
Author: User
Tags redis version

Introduction: As a rare, large-scale web site under the. NET Architecture, StackOverflow has published an article that introduces its technical system, the original link http://highscalability.com/blog/2011/3/3/ Stack-overflow-architecture-update-now-at-95-million-page-vi.html. As you can see from the text, the site uses Redis as its cache layer. And Sina Weibo has already used a lot of redis. As a new NoSQL database, Redis solves both the memcached persistence problem and the performance of the traditional memcached+mysql.

1 Redis Installation and configuration

At present, the operation of Redis on Windows is not stable, it is generally deployed under the Linux server, online can search many installation tutorials, this article will not repeat http://www.oschina.net/question/12_18065

2 Download Servicestack. Redis

Currently, the official Redis version does not support. NET direct connection and requires the use of some open source class libraries. The most popular is the Servicestack.redis,github link for Https://github.com/ServiceStack/ServiceStack.Redis

Click Download.zip on the right side of the page, unzip it after downloading, and find the required four DLLs under Build\release\monodevelop\servicestack.redis.

3 using Servicestack to connect Redis

Create a new VS project and introduce the above four DLLs, and then we can use C # to connect to the Redis database, one of the simplest examples:

4 at present Servicestack.redis is still developing and improving, so some method description is not very clear, so provide an already packaged class to use all of us,

Redis's network connection is similar to a traditional RDBMS, a long connection, a connection pool, where a long connection is used to connect

It is highly recommended to read the comments before use

  1 using System;  2 using System.Collections.Generic;  3 using System.Linq;  4 using System.Text;  5 using System.Threading.Tasks;  6 using Servicestack.redis; 7 namespace Testredis 8 {9 class Redishelper:idisposable {/*[email protected] All rights Re Served * author:mars * date:2013.08.27 * qq:258248340 * Servicestack.redis  Open source project for GitHub * Redis is a typical k/v database * Redis supports five types of data string,list,hash,set,sortedset 18 * * string is the simplest string type. * List is a list of strings, which are internally implemented with a doubly linked table, so you can support positive and negative indexes when getting/setting data 22 * or Use it as a stack structure. The hash type is a dictionary structure and the data type closest to the RDBMS, which stores the mapping of field and field values, but the field value can only be 25 * String type, hash type is suitable for storing objects          , we recommend using object categories and IDs to form key names, using fields to represent object properties, and Word 26 * Segment values to store property values, for example: Car:2 price, car:2 color Black, command format when hashing with Redis commands 27 * as follows: Hset key field value, that is, key, field name, field value * Set is a collection type that can be intersected in Redis and set and mutually exclusive operations 30         * Sorted set is based on a set of each element associated with a "score", we can 32 * to obtain the highest fraction of the top n elements, the specified fractional range of elements, the elements are different, but          Yes, the "score" can be the same. * Set is implemented with a hash list and a jump table, and the average speed to get data is O (log (N)) 34 * 35 * It is important to note that all Redis data types do not support nesting 36 * There is generally no distinction between insert and update operations in Redis, except that the return value of the command is different 37 * When the key is inserted, if it does not exist, it will be automatically created 38 * 39 * In the actual production environment, due to multi-threaded concurrency of the relationship, It is recommended to use connection pooling, this class is just for testing simple data Types 40 */41 42/* 43 * The following methods are basic setup data and fetch data */ static redisclient rediscli = null; //<summary> 47//Establish Redis long connection///</summary> 49//Exchange IP here for your own Redis instance         IP, if a password is provided, the third parameter is a password, string type is public static void CreateClient (string hostip,int port,string keyword) 51 {REDISCLI = = null) @ rediscli = new Redisclient (HostIP, Port, Keywor D); CreateClient (string hostip, int, port) 59        {REDISCLI = = null) REDISCLI = new Redisclient (HostIP, Port ); //private static Redisclient rediscli = new Redisclient ("192.168.101.165", 6379, "123456"); //<summary> 68///Get key, return string format//</summary>//<param NA Me= "key" ></param>//<returns></returns> getvaluestring public static string (s Tring key) ($ = rediscli.getvalue (key); Lue +//<summary> 81///Get key, return byte[] format &L//         t;/summary>//<param name= "key" ></param>//<returns></returns> 85      public static byte[] Getvaluebyte (string key) [byte[] value = Rediscli.get (key); 88       return value; *//<summary> 91///Get all fields under a hash key///</summary> 93/ <param name= "Hashid" ></param> 94//<returns></returns> public static list& Lt;string> gethashfields (String Hashid), {list<string> hashfields = Rediscli.gethashkey S (Hashid); 98 return hashfields; }100///&LT;SUMMARY&GT;101///For all values under a hash key 102///</summary>103// /<param name= "Hashid" ></param>104//<returns></returns>105 public static LIST&L T;string> gethashvalues (String Hashid) 106 {107 list<string> hashvalues = Rediscli.gethashkeys          (Hashid); 108 return hashvalues;109}110//<summary>111//Get hash key value of a field 112 </summary>113//<param name= "key" ></param>114//<param name= "field" ></param>115 public static string Gethashfield (string key, Strin          G field) 117 {String value = Rediscli.getvaluefromhash (key, field); 118 return value;119 }120///<summary>121///Set hash key value for a field 122///</summary>123/// Lt;param name= "key" ></param>124//<param name= "field" ></param>125//<param Nam         E= "value" ></param>126 public static void Sethashfield (String key, String field, String value) 127 {Rediscli.setentryinhash (Key, field, value); 129}130//<summary>131//Make a field Increase//</summary>133//<param name= "key" ></param>134//<param name= " Field "></param>135//<returns></returns>136 public static void Sethashincr (String k EY, string field, long INcre) 137 {138 Rediscli.incrementvalueinhash (key, field, Incre); 139}141//&LT;SU mmary>142////Add members to the list type data, add 143//</summary>144 to the bottom (right)////<param name= "Item" ; </param>145//<param name= "list" ></param>146 public static void Additemtolistright (ST Ring list, string item) 147 {148 Rediscli.additemtolist (list, item); 149}150//&LT;SU mmary>151////Add Members to list type data, add to the top (left)//</summary>153//<param name= "list" ; </param>154//<param name= "item" ></param>155 public static void Additemtolistleft (str         ing list, string item) 156 {157 Rediscli.lpush (list, Encoding.Default.GetBytes (item)); 158}159 &LT;SUMMARY&GT;160///Read all members from List type data 161//</summary>162 public static LIST&L T;string> Getallitems(String list) 163 {164 List<string> listmembers = rediscli.getallitemsfromlist (list); 165         return listmembers;166}167///<summary>168////From the list type data at the specified index, supports positive and negative indexes 169 </summary>170//<param name= "list" ></param>171//<returns></returns&gt ; 172 public static string Getitemfromlist (string list, int index) 173 {174 String item = Redisc Li. Getitemfromlist (list, index); 175 return item;176}177//<summary>178//to the bottom of the list  (right) bulk add data 179//</summary>180//<param name= "list" ></param>181//<param         Name= "Values" ></param>182 public static void Getrangetolist (string list, list<string> values) 183 {184 rediscli.addrangetolist (list, values); 185}186//<summary>187// Adding data to the collection 188/</summary>189//<param name= "item" ></param>190//<param name= "set" ></par am>191 public static void Getitemtoset (string item, string set) 192 {193 Rediscli.additemtos         ET (item, set); 194}195//<summary>196///Get all data in the collection 197//</summary>198 <param name= "Set" ></param>199//<returns></returns>200 public static Ha Shset<string> Getallitemsfromset (String set) 201 {202 hashset<string> items = Rediscli.geta Llitemsfromset (set); 203 return items;204}205//<summary>206//Get Fromset collection and its He sets different data 207//</summary>208//<param name= "Fromset" ></param>209//<para M name= "Toset" ></param>210//<returns></returns>211 public static hashset<string > Getsetdiff (String fRomset, params string[] toset) 212 {213 hashset<string> diff = rediscli.getdifferencesfromset (fro         MSet, Toset); 214 return diff;215}216//<summary>217//Get the set of all collections 218 </summary>219//<param name= "set" ></param>220//<returns></returns>2 + public static hashset<string> getsetunion (params string[] set) 222 {223 Hashset<str Ing> Union = rediscli.getunionfromsets (set); 224 return union;225}226//<summary>22 7///Get intersection of all sets 228//</summary>229//<param name= "set" ></param>230/         <returns></returns>231 public static hashset<string> Getsetinter (params string[] set) 232         {233 hashset<string> inter = rediscli.getintersectfromsets (set); 234 return inter;235 }236//&Lt;summary>237////Add elements to an ordered collection 238///</summary>239//<param name= "set" ></param&         gt;240//<param name= "value" ></param>241//<param name= "Score" ></param>242 public static void Additemtosortedset (string set,string value,long score) 243 {244 Rediscli.addite         Mtosortedset (Set,value,score); 245}246//<summary>247//To get the rank of a value in an ordered set, sorted in descending order of fractions 248 </summary>249//<param name= "set" ></param>250//<param name= "value" >&lt  ;/param>251//<returns></returns>252 public static int Getitemindexinsortedsetdesc (string             Set, String value) 253 {254 int index = REDISCLI.GETITEMINDEXINSORTEDSETDESC (set, value); 255 return index;256}257///<summary>258///The rank of a value in an ordered set, sorted in ascending order of fractions 259//&LT;/SU mmary>260// <param name= "Set" ></param>261///<param Name= "value" ></param>262//<returns             ></returns>263 public static int Getitemindexinsortedset (string set, String value) 264 {265 int index = Rediscli.getitemindexinsortedset (set, value); 266 return index;267}268///& lt;summary>269///</summary>271 a worthy score in an ordered collection/////<param name= "set" ></pa         ram>272//<param name= "value" ></param>273//<returns></returns>274 public static double Getitemscoreinsortedset (string set, String value) 275 {276 Double score = REDISCLI . Getitemscoreinsortedset (set, value); 277 return score;278}279//<summary>280/  Get all values for a ranking range in an ordered set 281//</summary>282//<param name= "set" ></param>283// <param name= "BeginrAnk "></param>284//<param name=" Endrank "></param>285//<returns></return         s>286 public static list<string> Getrangefromsortedset (string set,int beginrank, int endrank) 287  {288 list<string> valuelist=rediscli.getrangefromsortedset (Set,beginrank,endrank); 289 return valuelist;290}291///<summary>292///Get all values in a fractional range in an ordered set, ascending 293//</summary&         gt;294//<param name= "set" ></param>295//<param name= "Beginscore" ></param>296 <param name= "Endscore" ></param>297//<returns></returns>298 public s             Tatic list<string> Getrangefromsortedset (string set, double Beginscore, double endscore) 299 {300 list<string> valueList = Rediscli.getrangefromsortedsetbyhighestscore (set, Beginscore, Endscore); 301 Re      Turn valuelist;302   }303///<summary>304///Get all values in a fractional range in an ordered set, descending 305///</summary>306/// Lt;param name= "Set" ></param>307///<param name= "Beginscore" ></param>308//<para M name= "Endscore" ></param>309//<returns></returns>310 public static list<string > Getrangefromsortedsetdesc (String set, double Beginscore, double endscore) 311 {312 list<string& Gt         Vlauelist=rediscli.getrangefromsortedsetbylowestscore (Set,beginscore,endscore); 313 return vlaueList;314 }315 public void Dispose () 317 rediscli.dispose (); 318}319 320}321}

Here, in this article, I'll talk to you about connection pooling, locks, thread safety, and distributed mechanisms in Redis.

Author: Mars

Source: http://www.cnblogs.com/marsblog/

This article is based on the attribution-non-commercial use of the 3.0 China Mainland License Agreement published, welcome reprint, deduction or for commercial purposes, but must retain the attribution of this article Mars (including links)

Redis applications in the. NET Architecture (1)--using Servicestack to connect Redis (GO)

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.