1. 程式人生 > >C#使用Redis的基本操作

C#使用Redis的基本操作

一,引入dll

  1.ServiceStack.Common.dll

  2.ServiceStack.Interfaces.dll

  3.ServiceStack.Redis.dll

  4.ServiceStack.Text.dll

二,修改配置檔案

  在你的配置檔案中加入如下的程式碼:

<appSettings>
  <add key="RedisPath" value="127.0.0.1:6379"/>  todo:這裡配置自己redis的ip地址和埠號
</appSettings>

 

二,用到的工具類

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;
namespace RedisDemo
{
  /// <summary>
  /// RedisManager類主要是建立連結池管理物件的
  /// </summary>
  public class RedisManager
  {
    /// <summary>
    /// redis配置檔案資訊
    
/// </summary> private static string RedisPath = System.Configuration.ConfigurationSettings.AppSettings["RedisPath"]; private static PooledRedisClientManager _prcm; /// <summary> /// 靜態構造方法,初始化連結池管理物件 /// </summary> static RedisManager() { CreateManager(); }
/// <summary> /// 建立連結池管理物件 /// </summary> private static void CreateManager() { _prcm = CreateManager(new string[] { RedisPath }, new string[] { RedisPath }); } private static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts) { //WriteServerList:可寫的Redis連結地址。 //ReadServerList:可讀的Redis連結地址。 //MaxWritePoolSize:最大寫連結數。 //MaxReadPoolSize:最大讀連結數。 //AutoStart:自動重啟。 //LocalCacheTime:本地快取到期時間,單位:秒。 //RecordeLog:是否記錄日誌,該設定僅用於排查redis執行時出現的問題,如redis工作正常,請關閉該項。 //RedisConfigInfo類是記錄redis連線資訊,此資訊和配置檔案中的RedisConfig相呼應 // 支援讀寫分離,均衡負載 return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig { MaxWritePoolSize = 5, // “寫”連結池連結數 MaxReadPoolSize = 5, // “讀”連結池連結數 AutoStart = true, }); } private static IEnumerable<string> SplitString(string strSource, string split) { return strSource.Split(split.ToArray()); } /// <summary> /// 客戶端快取操作物件 /// </summary> public static IRedisClient GetClient() { if (_prcm == null) { CreateManager(); } return _prcm.GetClient(); } } }

 

 三,main方法執行儲存操作與讀取操作 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;
using ServiceStack.Redis.Support;
namespace RedisDemo
{
  class Program
  {
    static void Main(string[] args)
    {
      try
      {
        //獲取Redis操作介面
        IRedisClient Redis = RedisManager.GetClient();
        //放入記憶體
        Redis.Set<string>("my_name", "小張");
        Redis.Set<int>("my_age", 12);
        //儲存到硬碟
        Redis.Save();
        //釋放記憶體
        Redis.Dispose();
        //取出資料
        Console.WriteLine("取出剛才存進去的資料 \r\n 我的Name:{0}; 我的Age:{1}.",
          Redis.Get<string>("my_name"), Redis.Get<int>("my_age"));
        Console.ReadKey();
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message.ToString());
        Console.ReadKey();
      }
    }
  }
}

 

完活,下面是執行後的結果