C#實用技能篇

Redis配置文件詳解html

 

若是不指定配置文件,redis也能夠啓動,此時,redis使用默認的內置配置。不過在正式環境,經常經過配置文件【一般叫redis.conf】來配置redis。git

redis.conf配置格式以下:github

 

 
  1. keyword argument1 argument2 ... argumentN  


redis.conf配置參數:web

 

1)daemonize on|yesredis

redis默認不是以守護進程的方式運行,能夠經過該配置項修改,使用yes時,啓用守護進程算法

2)pidfile /var/run/redis_6379.pid數據庫

redis以守護進程方式運行時,系統默認會把pid寫入/var/run/redis.pid,能夠經過pidfile指定pid文件windows

3)port 6379api

redis默認監聽6379端口,能夠經過port指定redis要監聽的端口緩存

4)bind 127.0.0.1

綁定主機地址

5)unixsocket /tmp/redis.sock

指定redis監聽的unix socket 路徑

6)timeout 300

當客戶端閒置多長時間,關閉鏈接,單位秒

7)loglevel verbose|debug|notice|warning

指定日誌記錄級別,默認是verbose

8)logfile /var/log/redis_6379.log

日誌記錄文件,默認是標準輸出stdout,若是redis以守護進程方式運行,logfile 配置爲stdout時,logs將要輸出到/dev/null

9)syslog-enabled no|yes

當配置爲yes時,日誌輸出到系統日誌,默認是no

10)syslog-ident redis

指定syslog的標示符

11)syslog-facility local0

指定syslog設備(facility),必須是user或則local0到local7

12)databases 16

設置redis中數據庫的個數,默認數據庫是DB 0,能夠經過select <dbid>,選擇使用的數據庫。dbis大於等於0,小於等於databases -1 【這裏是16-1】

13)save <seconds> <changes>

指定多長時間內,有多少次更新操做時,將數據同步到數據庫文件,能夠多個條件配合,系統默認配置以下:

 

[plain]  view plain  copy
 
  1. save 900 1 #900秒 1個修改  
  2. save 300 10 #300秒 10個更新  
  3. save 60 10000<span style="white-space:pre"> </span>#60秒 10000個更新  

注意,若是不持久化【不把數據寫入磁盤】,註釋掉save便可。 

14)rdbcompression yes|no

 

數據dump到數據文件時,系統是否壓縮string對象數據,系統默認是yes。若是爲了節省cpu,能夠設置爲no,此時數據文件比用LZF壓縮時要大
15)dbfilename dump.rdb

指定數據庫文件名,默認是dump.rdb

16)dir /var/lib/redis/6379

指定本地數據庫存放目錄

17)slaveof <masterip> <masterport>

當本機是slave服務時,設置master服務的ip和端口

18)masterauth <master-password>

當master服務設置了密碼時,slave服務鏈接master的密碼。若是配置不對,slave服務請求將被拒絕

19)slave-serve-stale-data yes|no

當slave和master之間的鏈接斷開或slave正在於master同步時,若是有slave請求,當slave-serve-stale-data配置爲yes時,slave能夠相應客戶端請求;當爲no時,slave將要響應錯誤,默認是yes

20)requirepass foobared

設置redis鏈接密碼

21)maxclients 128

設置同一時間客戶端最大鏈接數,默認是無限制。若是設置maxclients 0 時,表示不限制

22)maxmemory <bytes>

指定redis最大內存限制,redis在啓動時,會把數據加載到內存中,達到最大內存後,redis會先清除已到期或將過時的key,仍然到達最大內存設置,將沒法再進行寫入操做,但仍然能夠進行讀操做

23)maxmemory-policy volatile-lru|allkeys-lru|volatile-random|allkeys->random|volatile-ttl|noeviction

當redis使用內存達到最大時,使用哪一種策略移除內存中數據

24)appendonly no|yes

指定是否在每次更新操做後進行日誌記錄,默認配置是no,即在採用異步方式把數據寫入到磁盤,若是不開啓,可能會在斷電時致使部分數據丟失

25)appendfilename appendonly.aof

指定更新日誌文件名【aof日誌】,默認爲appendonly.aof

26)appendfsync everysec|no|aways

指定更新日誌條件,no表示等操做系統進行數據緩存同步到磁盤的aof文件(快)always表示每次更新操做後手動調用fsync將數據寫到磁盤的aof文件(慢,安全)

everysec,表示每秒同步一次(拆中,默認值)

27)slowlog-log-slower-than 10000

配置記錄慢日誌的條件,單位是微妙,當是負值時,關閉慢日誌記錄,當是0時,記錄全部操做

28)slowlog-max-len 1024

配置記錄慢查詢的最大條數

29)hash-max-zipmap-entries 512

配置最大元素數,當超過該配置數據時,redis採用特殊hash算法

30)hash-max-zipmap-value 64

配置最大元素值,當草果配置值時,採用特殊hash算法

31)activerehashing yes

指定是否激活充值hash,默認開啓

能夠經過下面命令使用配置文件redis.conf啓動redis服務

 

Redis安裝管理

C#客戶端Redis服務器的分佈式緩存

在這篇文章中,我想介紹我知道的一種最緊湊的安裝和配置Redis服務器的方式。另外,我想簡短地概述一下在.NET / C#客戶端下Redis hash(哈希類型)和list(鏈表)的使用。

做者:小峯來源:碼農網|2015-08-17 09:48

 

介紹

在這篇文章中,我想介紹我知道的一種最緊湊的安裝和配置Redis服務器的方式。另外,我想簡短地概述一下在.NET / C#客戶端下Redis hash(哈希類型)和list(鏈表)的使用。

在這篇文章主要講到:

  • 安裝Redis服務器(附完整的應用程序文件設置

  • Redis服務器保護(配置身份驗證)

  • 配置服務器複製

  • 從C#應用程序訪問緩存

  • 使用Redis ASP.NET會話狀態

  • Redis 集合(Set)、列表(List)和事務處理用法示例

  • 說明附加的源(Redis Funq LoC MVC項目:舉例)

  • 緩存的優化思路

背景

Redis是最快也是功能最豐富的內存Key-Value數據存儲系統之一。

缺點

  • 沒有本地數據緩存(如在Azure緩存同步本地數據緩存)

  • 沒有徹底集羣化的支持(不過,可能今年年末會實現)

優勢

  • 易於配置

  • 使用簡單

  • 高性能

  • 支持不一樣的數據類型(如hash(哈希類型)、list(鏈表)、set(集合)、sorted set(有序集))

  • ASP.NET會話集成

  • Web UI用於瀏覽緩存內容

下面我將簡單說明如何在服務器上安裝和配置Redis,並用C#使用它。

Redis的安裝

https://github.com/dmajkic/redis/downloads(win32 win64直接連接)下載二進制文件,解包檔案到應用程序目錄(如C:\Program Files\Redis)

下載從https://github.com/kcherenkov/redis-windows-service/downloads編譯的Redis服務,而後複製到程序文件夾(如C:\Program Files\Redis)。若是配置文件丟失,也能夠下載複製到應用程序目錄。有效的Redis配置文件的範例在https://raw.github.com/antirez/redis/2.6/redis.conf

Redis應用程序的完整文件也能夠從壓縮文件(x64)獲得。

當你擁有了全套的應用程序文件(以下圖所示),

redis application folder conten

導航到應用程序目錄,而後運行如下命令:

sc create %name% binpath= "\"%binpath%\" %configpath%" start= "auto" DisplayName= "Redis"

其中:

  • %name%——服務實例的名稱,例如:redis-instance;

  • %binpath%——到項目exe文件的路徑,例如:C:\Program Files\Redis\RedisService_1.1.exe;

  • %configpath%——到Redis配置文件的路徑,例如:C:\Program Files\Redis\redis.conf;

舉例:

sc create Redis start= auto DisplayName= Redis binpath= "\"C:\Program Files\Redis\RedisService_1.1.exe\
" \"C:\Program Files\Redis\redis.conf\""

即應該是這樣的:

請確保有足夠的權限啓動該服務。安裝完畢後,請檢查該服務是否建立成功,當前是否正在運行:

或者,你可使用安裝程序(我沒試過):https://github.com/rgl/redis/downloads

Redis服務器保護:密碼,IP過濾

保護Redis服務器的主要方式是使用Windows防火牆或活躍的網絡鏈接屬性設置IP過濾。此外,還可使用Redis密碼設置額外保護。這須要用下面的方式更新Redis配置文件(redis.conf):

首先,找到這行:

# requirepass foobared

刪除開頭的#符號,用新密碼替換foobared:

requirepass foobared

而後,從新啓動Redis Windows服務!

當具體使用客戶端的時候,使用帶密碼的構造函數:

RedisClient client = new RedisClient(serverHost, port, redisPassword);

Redis服務器複製(主—從配置)

Redis支持主從同步,即,每次主服務器修改,從服務器獲得通知,並自動同步。大多複製用於讀取(但不能寫)擴展和數據冗餘和服務器故障轉移。設 置兩個Redis實例(在相同或不一樣服務器上的兩個服務),而後配置其中之一做爲從站。爲了讓Redis服務器實例是另外一臺服務器的從屬,能夠這樣更改配 置文件:

找到如下代碼:

# slaveof <masterip> <masterport>

替換爲:

slaveof 192.168.1.1 6379

(能夠自定義指定主服務器的真實IP和端口)。若是主服務器配置爲須要密碼(驗證),能夠以下所示改變redis.conf,找到這一行代碼:

# masterauth <master-password>

刪除開頭的#符號,用主服務器的密碼替換<master-password>,即:

masterauth mastpassword

如今這個Redis實例能夠被用來做爲主服務器的只讀同步副本。

用C#代碼使用Redis緩存

用C#代碼使用Redis運行Manage NuGet包插件,找到ServiceStack.Redis包,並進行安裝。

直接從實例化客戶端使用Set/Get方法示例:

  1. string host = "localhost"; 
  2. string elementKey = "testKeyRedis"; 
  3.  
  4. using (RedisClient redisClient = new RedisClient(host)) 
  5.       if (redisClient.Get<string>(elementKey) == null) 
  6.       { 
  7.            // adding delay to see the difference 
  8.            Thread.Sleep(5000); 
  9.            // save value in cache 
  10.            redisClient.Set(elementKey, "some cached value"); 
  11.       } 
  12.       // get value from the cache by key 
  13.       message = "Item value is: " + redisClient.Get<string>("some cached value"); 

類型化實體集更有意思和更實用,這是由於它們操做的是確切類型的對象。在下面的代碼示例中,有兩個類分別定義爲Phone和Person——phone的主人。每一個phone實例引用它的主人。下面的代碼演示咱們如何經過標準添加、刪除和發現緩存項:

  1. public class Phone 
  2.    public int Id { get; set; } 
  3.    public string Model { get; set; } 
  4.    public string Manufacturer { get; set; } 
  5.    public Person Owner { get; set; } 
  6.  
  7. public class Person 
  8.     public int Id { get; set; } 
  9.     public string Name { get; set; } 
  10.     public string Surname { get; set; } 
  11.     public int Age { get; set; } 
  12.     public string Profession { get; set; } 
  13.  
  14. using (RedisClient redisClient = new RedisClient(host)) 
  15.      IRedisTypedClient<phone> phones = redisClient.As<phone>(); 
  16.      Phone phoneFive = phones.GetValue("5"); 
  17.      if (phoneFive == null) 
  18.      { 
  19.           // make a small delay 
  20.           Thread.Sleep(5000); 
  21.           // creating a new Phone entry 
  22.           phoneFive = new Phone 
  23.           { 
  24.                Id = 5, 
  25.                Manufacturer = "Motorolla", 
  26.                Model = "xxxxx", 
  27.                Owner = new Person 
  28.                { 
  29.                     Id = 1, 
  30.                     Age = 90, 
  31.                     Name = "OldOne", 
  32.                     Profession = "sportsmen", 
  33.                     Surname = "OldManSurname" 
  34.                } 
  35.           }; 
  36.           // adding Entry to the typed entity set 
  37.           phones.SetEntry(phoneFive.Id.ToString(), phoneFive); 
  38.      } 
  39.      message = "Phone model is " + phoneFive.Manufacturer; 
  40.      message += "Phone Owner Name is: " + phoneFive.Owner.Name; 

在上面的例子中,咱們實例化了輸入端IRedisTypedClient,它與緩存對象的特定類型——Phone類型一塊兒工做。

Redis ASP.NET會話狀態

要用Redis提供商配置ASP.NET會話狀態,添加新文件到你的Web項目,命名爲RedisSessionStateProvider.cs,能夠從https://github.com/chadman/redis-service-provider/raw/master/RedisProvider/SessionProvider/RedisSessionProvider.cs複製代碼,而後添加或更改配置文件中的如下部分(sessionState標籤已經內置於system.web標籤),或者你也能夠下載附加來源和複製代碼。

  1. <sessionstate timeout="1" mode="Custom" 
  2. customprovider="RedisSessionStateProvider" cookieless="false"> 
  3.       <providers> 
  4.         <add name="RedisSessionStateProvider" writeexceptionstoeventlog="false" 
  5.         type="RedisProvider.SessionProvider.CustomServiceProvider" 
  6.         server="localhost" port="6379" password="pasword"> 
  7.       </add> </providers> 
  8. </sessionstate> 

注意,此密碼是能夠選擇的,看服務器是否須要認證。它必須被真實的值替換或刪除,若是Redis服務器不須要身份驗證,那麼服務器屬性和端口得由具體的數值代替(默認端口爲6379)。而後在項目中,你纔可使用會話狀態:

  1. // in the Global.asax 
  2. public class MvcApplication1 : System.Web.HttpApplication 
  3.     protected void Application_Start() 
  4.     { 
  5.         //.... 
  6.     } 
  7.  
  8.     protected void Session_Start() 
  9.     { 
  10.         Session["testRedisSession"] = "Message from the redis ression"; 
  11.     } 
  12.  
  13. 在Home controller(主控制器): 
  14.  
  15. public class HomeController : Controller 
  16.     public ActionResult Index() 
  17.     { 
  18.        //... 
  19.        ViewBag.Message = Session["testRedisSession"]; 
  20.        return View(); 
  21.     } 
  22. //... 

結果:

ASP.NET輸出緩存提供者,而且Redis能夠用相似的方式進行配置。

Redis Set(集合)和List(列表)

主要要注意的是,Redis列表實現IList<T>,而Redis集合實現ICollection<T>。下面來講說如何使用它們。

當須要區分相同類型的不一樣分類對象時,使用列表。例如,咱們有「mostSelling(熱銷手機)」和「oldCollection(回收手機)」兩個列表:

  1. string host = "localhost"; 
  2. using (var redisClient = new RedisClient(host)) 
  3.     //Create a 'strongly-typed' API that makes all Redis Value operations to apply against Phones 
  4.     IRedisTypedClient<phone> redis = redisClient.As<phone>(); 
  5.  
  6.     IRedisList<phone> mostSelling = redis.Lists["urn:phones:mostselling"]; 
  7.     IRedisList<phone> oldCollection = redis.Lists["urn:phones:oldcollection"]; 
  8.  
  9.     Person phonesOwner = new Person 
  10.         { 
  11.             Id = 7, 
  12.             Age = 90, 
  13.             Name = "OldOne", 
  14.             Profession = "sportsmen", 
  15.             Surname = "OldManSurname" 
  16.         }; 
  17.  
  18.     // adding new items to the list 
  19.     mostSelling.Add(new Phone 
  20.             { 
  21.                 Id = 5, 
  22.                 Manufacturer = "Sony", 
  23.                 Model = "768564564566", 
  24.                 Owner = phonesOwner 
  25.             }); 
  26.  
  27.     oldCollection.Add(new Phone 
  28.             { 
  29.                 Id = 8, 
  30.                 Manufacturer = "Motorolla", 
  31.                 Model = "324557546754", 
  32.                 Owner = phonesOwner 
  33.             }); 
  34.  
  35.     var upgradedPhone  = new Phone 
  36.     { 
  37.         Id = 3, 
  38.         Manufacturer = "LG", 
  39.         Model = "634563456", 
  40.         Owner = phonesOwner 
  41.     }; 
  42.  
  43.     mostSelling.Add(upgradedPhone); 
  44.  
  45.     // remove item from the list 
  46.     oldCollection.Remove(upgradedPhone); 
  47.  
  48.     // find objects in the cache 
  49.     IEnumerable<phone> LGPhones = mostSelling.Where(ph => ph.Manufacturer == "LG"); 
  50.  
  51.     // find specific 
  52.     Phone singleElement = mostSelling.FirstOrDefault(ph => ph.Id == 8); 
  53.  
  54.     //reset sequence and delete all lists 
  55.     redis.SetSequence(0); 
  56.     redisClient.Remove("urn:phones:mostselling"); 
  57.     redisClient.Remove("urn:phones:oldcollection"); 

當須要存儲相關的數據集和收集統計信息,例如answer -> queustion給答案或問題投票時,Redis集合就很是好使。假設咱們有不少的問題(queustion)和答案(answer ),須要將它們存儲在緩存中。使用Redis,咱們能夠這麼作:

  1. /// <summary> 
  2. /// Gets or sets the Redis Manager. The built-in IoC used with ServiceStack autowires this property. 
  3. /// </summary> 
  4. IRedisClientsManager RedisManager { get; set; } 
  5. /// <summary> 
  6. /// Delete question by performing compensating actions to 
  7. /// StoreQuestion() to keep the datastore in a consistent state 
  8. /// </summary> 
  9. /// <param name="questionId"> 
  10. public void DeleteQuestion(long questionId) 
  11.     using (var redis = RedisManager.GetClient()) 
  12.     { 
  13.         var redisQuestions = redis.As<question>(); 
  14.  
  15.         var question = redisQuestions.GetById(questionId); 
  16.         if (question == null) return; 
  17.  
  18.         //decrement score in tags list 
  19.         question.Tags.ForEach(tag => redis.IncrementItemInSortedSet("urn:tags", tag, -1)); 
  20.  
  21.         //remove all related answers 
  22.         redisQuestions.DeleteRelatedEntities<answer>(questionId); 
  23.  
  24.         //remove this question from user index 
  25.         redis.RemoveItemFromSet("urn:user>q:" + question.UserId, questionId.ToString()); 
  26.  
  27.         //remove tag => questions index for each tag 
  28.         question.Tags.ForEach("urn:tags>q:" + tag.ToLower(), questionId.ToString())); 
  29.  
  30.         redisQuestions.DeleteById(questionId); 
  31.     } 
  32.  
  33. public void StoreQuestion(Question question) 
  34.     using (var redis = RedisManager.GetClient()) 
  35.     { 
  36.         var redisQuestions = redis.As<question>(); 
  37.  
  38.         if (question.Tags == null) question.Tags = new List<string>(); 
  39.         if (question.Id == default(long)) 
  40.         { 
  41.             question.Id = redisQuestions.GetNextSequence(); 
  42.             question.CreatedDate = DateTime.UtcNow; 
  43.  
  44.             //Increment the popularity for each new question tag 
  45.             question.Tags.ForEach(tag => redis.IncrementItemInSortedSet("urn:tags", tag, 1)); 
  46.         } 
  47.  
  48.         redisQuestions.Store(question); 
  49.         redisQuestions.AddToRecentsList(question); 
  50.         redis.AddItemToSet("urn:user>q:" + question.UserId, question.Id.ToString()); 
  51.  
  52.         //Usage of tags - Populate tag => questions index for each tag 
  53.         question.Tags.ForEach(tag => redis.AddItemToSet 
  54.         ("urn:tags>q:" + tag.ToLower(), question.Id.ToString())); 
  55.     } 
  56.  
  57. /// <summary> 
  58. /// Delete Answer by performing compensating actions to 
  59. /// StoreAnswer() to keep the datastore in a consistent state 
  60. /// </summary> 
  61. /// <param name="questionId"> 
  62. /// <param name="answerId"> 
  63. public void DeleteAnswer(long questionId, long answerId) 
  64.     using (var redis = RedisManager.GetClient()) 
  65.     { 
  66.         var answer = redis.As<question>().GetRelatedEntities<answer> 
  67.         (questionId).FirstOrDefault(x => x.Id == answerId); 
  68.         if (answer == null) return; 
  69.  
  70.         redis.As<question>().DeleteRelatedEntity<answer>(questionId, answerId); 
  71.  
  72.         //remove user => answer index 
  73.         redis.RemoveItemFromSet("urn:user>a:" + answer.UserId, answerId.ToString()); 
  74.     } 
  75.  
  76. public void StoreAnswer(Answer answer) 
  77.     using (var redis = RedisManager.GetClient()) 
  78.     { 
  79.         if (answer.Id == default(long)) 
  80.         { 
  81.             answer.Id = redis.As<answer>().GetNextSequence(); 
  82.             answer.CreatedDate = DateTime.UtcNow; 
  83.         } 
  84.  
  85.         //Store as a 'Related Answer' to the parent Question 
  86.         redis.As<question>().StoreRelatedEntities(answer.QuestionId, answer); 
  87.         //Populate user => answer index 
  88.         redis.AddItemToSet("urn:user>a:" + answer.UserId, answer.Id.ToString()); 
  89.     } 
  90.  
  91. public List<answer> GetAnswersForQuestion(long questionId) 
  92.     using (var redis = RedisManager.GetClient()) 
  93.     { 
  94.         return redis.As<question>().GetRelatedEntities<answer>(questionId); 
  95.     } 
  96.  
  97. public void VoteQuestionUp(long userId, long questionId) 
  98.     //Populate Question => User and User => Question set indexes in a single transaction 
  99.     RedisManager.ExecTrans(trans => 
  100.     { 
  101.         //Register upvote against question and remove any downvotes if any 
  102.         trans.QueueCommand(redis => 
  103.         redis.AddItemToSet("urn:q>user+:" + questionId, userId.ToString())); 
  104.         trans.QueueCommand(redis => 
  105.         redis.RemoveItemFromSet("urn:q>user-:" + questionId, userId.ToString())); 
  106.  
  107.         //Register upvote against user and remove any downvotes if any 
  108.         trans.QueueCommand(redis => 
  109.         redis.AddItemToSet("urn:user>q+:" + userId, questionId.ToString())); 
  110.         trans.QueueCommand(redis => 
  111.         redis.RemoveItemFromSet("urn:user>q-:" + userId, questionId.ToString())); 
  112.     }); 
  113.  
  114. public void VoteQuestionDown(long userId, long questionId) 
  115.     //Populate Question => User and User => Question set indexes in a single transaction 
  116.     RedisManager.ExecTrans(trans => 
  117.     { 
  118.         //Register downvote against question and remove any upvotes if any 
  119.         trans.QueueCommand(redis => 
  120.         redis.AddItemToSet("urn:q>user-:" + questionId, userId.ToString())); 
  121.         trans.QueueCommand(redis => 
  122.         redis.RemoveItemFromSet("urn:q>user+:" + questionId, userId.ToString())); 
  123.  
  124.         //Register downvote against user and remove any upvotes if any 
  125.         trans.QueueCommand(redis => 
  126.         redis.AddItemToSet"urn:user>q-:" + userId, questionId.ToString())); 
  127.         trans.QueueCommand(redis => 
  128.         redis.RemoveItemFromSet("urn:user>q+:" + userId, questionId.ToString())); 
  129.     }); 
  130.  
  131. public void VoteAnswerUp(long userId, long answerId) 
  132.     //Populate Question => User and User => Question set indexes in a single transaction 
  133.     RedisManager.ExecTrans(trans => 
  134.     { 
  135.         //Register upvote against answer and remove any downvotes if any 
  136.         trans.QueueCommand(redis => 
  137.         redis.AddItemToSet("urn:a>user+:" + answerId, userId.ToString())); 
  138.         trans.QueueCommand(redis => 
  139.         redis.RemoveItemFromSet("urn:a>user-:" + answerId, userId.ToString())); 
  140.  
  141.         //Register upvote against user and remove any downvotes if any 
  142.         trans.QueueCommand(redis => 
  143.         redis.AddItemToSet("urn:user>a+:" + userId, answerId.ToString())); 
  144.         trans.QueueCommand(redis => 
  145.         redis.RemoveItemFromSet("urn:user>a-:" + userId, answerId.ToString())); 
  146.     }); 
  147.  
  148. public void VoteAnswerDown(long userId, long answerId) 
  149.     //Populate Question => User and User => Question set indexes in a single transaction 
  150.     RedisManager.ExecTrans(trans => 
  151.     { 
  152.         //Register downvote against answer and remove any upvotes if any 
  153.         trans.QueueCommand(redis => 
  154.         redis.AddItemToSet("urn:a>user-:" + answerId, userId.ToString())); 
  155.         trans.QueueCommand(redis => 
  156.         redis.RemoveItemFromSet("urn:a>user+:" + answerId, userId.ToString())); 
  157.  
  158.         //Register downvote against user and remove any upvotes if any 
  159.         trans.QueueCommand(redis => 
  160.         redis.AddItemToSet("urn:user>a-:" + userId, answerId.ToString())); 
  161.         trans.QueueCommand(redis => 
  162.         redis.RemoveItemFromSet("urn:user>a+:" + userId, answerId.ToString())); 
  163.     }); 
  164.  
  165. public QuestionResult GetQuestion(long questionId) 
  166.     var question = RedisManager.ExecAs<question> 
  167.     (redisQuestions => redisQuestions.GetById(questionId)); 
  168.     if (question == null) return null; 
  169.  
  170.     var result = ToQuestionResults(new[] { question })[0]; 
  171.     var answers = GetAnswersForQuestion(questionId); 
  172.     var uniqueUserIds = answers.ConvertAll(x => x.UserId).ToHashSet(); 
  173.     var usersMap = GetUsersByIds(uniqueUserIds).ToDictionary(x => x.Id); 
  174.  
  175.     result.Answers = answers.ConvertAll(answer => 
  176.         new AnswerResult { Answer = answer, User = usersMap[answer.UserId] }); 
  177.  
  178.     return result; 
  179.  
  180. public List<user> GetUsersByIds(IEnumerable<long> userIds) 
  181.     return RedisManager.ExecAs<user>(redisUsers => redisUsers.GetByIds(userIds)).ToList(); 
  182.  
  183. public QuestionStat GetQuestionStats(long questionId) 
  184.     using (var redis = RedisManager.GetReadOnlyClient()) 
  185.     { 
  186.         var result = new QuestionStat 
  187.         { 
  188.             VotesUpCount = redis.GetSetCount("urn:q>user+:" +questionId), 
  189.             VotesDownCount = redis.GetSetCount("urn:q>user-:" + questionId) 
  190.         }; 
  191.         result.VotesTotal = result.VotesUpCount - result.VotesDownCount; 
  192.         return result; 
  193.     } 
  194.  
  195. public List<tag> GetTagsByPopularity(int skip, int take) 
  196.     using (var redis = RedisManager.GetReadOnlyClient()) 
  197.     { 
  198.         var tagEntries = redis.GetRangeWithScoresFromSortedSetDesc("urn:tags", skip, take); 
  199.         var tags = tagEntries.ConvertAll(kvp => new Tag { Name = kvp.Key, Score = (int)kvp.Value }); 
  200.         return tags; 
  201.     } 
  202.  
  203. public SiteStats GetSiteStats() 
  204.     using (var redis = RedisManager.GetClient()) 
  205.     { 
  206.         return new SiteStats 
  207.         { 
  208.             QuestionsCount = redis.As<question>().TypeIdsSet.Count, 
  209.             AnswersCount = redis.As<answer>().TypeIdsSet.Count, 
  210.             TopTags = GetTagsByPopularity(0, 10) 
  211.         }; 
  212.     } 

附加資源說明

項目中引用的一些包在packages.config文件中配置。

Funq IoC的相關配置,以及註冊類型和當前控制器目錄,在Global.asax文件中配置。

基於IoC的緩存使用以及Global.asax能夠打開如下URL:http://localhost:37447/Question/GetQuestions?tag=test 查看。

你能夠將tag字段設置成test3,test1,test2等。

Redis緩存配置——在web config文件(<system.web><sessionState>節點)以及RedisSessionStateProvider.cs文件中。

在MVC項目中有不少待辦事項,所以,若是你想改進/繼續,請更新,並上傳。

若是有人能提供使用Redis(以及Funq IOC)緩存的MVC應用程序示例,本人將不勝感激。Funq IOC已經配置,使用示例已經在Question controller中。

注:部分取樣於「ServiceStack.Examples-master」解決方案。

結論。優化應用程序緩存以及快速本地緩存

因爲Redis並不在本地存儲(也不在本地複製)數據,那麼經過在本地緩存區存儲一些輕量級或用戶依賴的對象(跳過序列化字符串和客戶端—服務端數據轉換)來優化性能是有意義的。例如,在Web應用中,對於輕量級的對象使用’System.Runtime.Caching.ObjectCache‘ 會更好——用戶依賴,而且應用程序時常要用。不然,當常常性地須要使用該對象時,就必須在分佈式Redis緩存中存儲大量容積的內容。用戶依賴的對象舉例——我的資料信息,個性化信息 。經常使用對象——本地化數據,不一樣用戶之間的共享信息,等等。

下載源代碼(Redis Funq LoC MVC 4版本)

連接

如何運行Redis服務:

https://github.com/kcherenkov/redis-windows-service

文檔:

http://redis.io/documentation

.NET / C#示例:

https://github.com/ServiceStack/ServiceStack.Examples

關於如何用C#在Windows上使用Redis的好建議:

http://maxivak.com/getting-started-with-redis-and-asp-net-mvc-under-windows/:

http://www.piotrwalat.net/using-redis-with-asp-net-web-api/

關於Redis:

https://github.com/ServiceStack/ServiceStack.Redis

Azure緩存

http://kotugoroshko.blogspot.ae/2013/07/windows-azure-caching-integration.html

許可證

這篇文章,以及任何相關的源代碼和文件,依據The Code Project Open License (CPOL)。

譯文連接:http://www.codeceo.com/article/distributed-caching-redis-server.html
英文原文:Distributed Caching using Redis Server with .NET/C# Client

 

園內博客簡單安裝Redis方法

windows下安裝redis

一、redis簡介
redis是一個key-value存儲系統。和Memcached相似,它支持存儲的value類型相對更多,包括string(字符串)、list(鏈表)、set(集合)、zset(sorted set --有序集合)和hashs(哈希類型)。這些數據類型都支持push/pop、add/remove及取交集並集和差集及更豐富的操做,並且這些操做都是原子性的。在此基礎上,redis支持各類不一樣方式的排序。與memcached同樣,爲了保證效率,數據都是緩存在內存中。區別的是redis會週期性的把更新的數據寫入磁盤或者把修改操做寫入追加的記錄文件,而且在此基礎上實現了master-slave(主從)同步。

Redis 是一個高性能的key-value數據庫。 redis的出現,很大程度補償了memcached這類key/value存儲的不足,在部分場合能夠對關係數據庫起到很好的補充做用。它提供了Python,Ruby,Erlang,PHP客戶端,使用很方便。

二、windows下安裝redis
下載地址https://github.com/dmajkic/redis/downloads。下載到的Redis支持32bit和64bit。根據本身實際狀況選擇,我選擇32bit。把32bit文件內容拷貝到須要安裝的目錄下,好比:D:\dev\redis-2.4.5。

打開一個cmd窗口,使用cd命令切換到指定目錄(D:\dev\redis-2.4.5)運行 redis-server.exe redis.conf 。運行之後出現以下界面。

這就說明Redis服務端已經安裝成功。

從新打開一個cmd窗口,使用cd命令切換到指定目錄(D:\dev\redis-2.4.5)運行 redis-cli.exe -h 127.0.0.1 -p 6379 -a 123456,其中 127.0.0.1是本地ip,6379是redis服務端的默認端口,123456是redis密碼。運行成功以下圖所示。
這樣,Redis windows環境下搭建已經完成,是否是很簡單。

這樣,Redis windows環境下搭建已經完成,是否是很簡單。

環境已經搭建好,總得測試下吧。好比:存儲一個key爲test,value爲hello word的字符串,而後獲取key值。
正確輸出 hell word,測試成功!

相關文章
相關標籤/搜索