Redis安裝及C#調用

來源:互聯網
上載者:User

標籤:format   解決   size   tor   man   下載   ges   時間   exp   

一、Redis簡介

             Redis是一個開源(BSD許可),記憶體儲存的資料結構伺服器,可用作資料庫,快取和訊息佇列代理。它支援字串、雜湊表、列表、集合、有序集合,位元影像,hyperloglogs等資料類型。內建複製、Lua指令碼、LRU收回、事務以及不同層級磁碟持久化功能,同時通過Redis Sentinel提供高可用,通過Redis Cluster提供自動分區。sd 

Redis官網上相關安裝、命令、配置等資訊寫的已經非常清楚(查看官網) 我就簡單介紹下。

二、下載安裝

            (1)下載

              Windows 環境產生好的檔案 (這裡版本比較老舊。你可以通過其他途徑下載別人產生好的檔案。這裡有redis-2.8.17 ), 這裡版本可能已經比較老舊,新版本可以自己下載源碼產生github.com(msvs檔案夾裡有解決方案可以用Vs2013產生,這裡需要更新到update5)。

            下載完檔案解壓目錄如下:

             

    (2)安裝:

     設定檔中幾個比較常用設定檔

      1. port 6379   連接埠號碼  

                2. bind 127.0.0.1  IP   

                3. requirepass 訪問的密碼  

                4. maxheap 記得把這個配置節點開啟,否者redis 服務無法啟動。例如maxheap 1024000000(我自己用3.0.504測試時需要注釋掉這個節點)  

                5. timeout:請求逾時時間  

 

其他配置說明。設定檔中有比較清楚的英文描述。看不懂英文?。沒關係。下載中有配中文描述。

配置好設定檔。直接點擊startup.bat就可以了。這時你會看到如下

當你看到這個頁面的時候說明。你的服務已經成功啟動了。(這個頁面不能關。關了服務就停止了)

如果沒有一閃而沒。可能你配置或在其他錯誤。我們就老老實實的輸入cmd-》檔案目錄-》執行命令。根據日誌找問題並解決問題

下面我們來做個儲存測試。

另開個視窗(服務視窗不能關閉)

測試結果如下

用戶端語句如下

           $ redis-cli -h host -p port -a password  

           如果需要做多台機器負載平衡只需要在另一台機器上配置資訊
           # slaveof <masterip> <masterport> 這個節點配置上就可以了。

三、C#調用

1、下載相關dll

      

    2、常用方法整理

public class RedisCacheHelper  {      private static readonly PooledRedisClientManager pool = null;      private static readonly string[] writeHosts = null;      private static readonly string[] readHosts = null;      public static int RedisMaxReadPool = int.Parse(ConfigurationManager.AppSettings["redis_max_read_pool"]);      public static int RedisMaxWritePool = int.Parse(ConfigurationManager.AppSettings["redis_max_write_pool"]);      static RedisCacheHelper()      {          var redisWriteHost = ConfigurationManager.AppSettings["redis_server_write"];          var redisReadHost = ConfigurationManager.AppSettings["redis_server_read"];          if (!string.IsNullOrEmpty(redisWriteHost))          {              writeHosts = redisWriteHost.Split(‘,‘);              readHosts = redisReadHost.Split(‘,‘);              if (readHosts.Length > 0)              {                  pool = new PooledRedisClientManager(writeHosts, readHosts,                      new RedisClientManagerConfig()                      {                          MaxWritePoolSize = RedisMaxWritePool,                          MaxReadPoolSize = RedisMaxReadPool,                            AutoStart = true                      });              }          }      }      public static void Add<T>(string key, T value, DateTime expiry)      {          if (value == null)          {              return;          }            if (expiry <= DateTime.Now)          {              Remove(key);                return;          }            try          {              if (pool != null)              {                  using (var r = pool.GetClient())                  {                      if (r != null)                      {                          r.SendTimeout = 1000;                          r.Set(key, value, expiry - DateTime.Now);                      }                  }              }          }          catch (Exception ex)          {              string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "儲存", key);          }        }        public static void Add<T>(string key, T value)      {          RedisCacheHelper.Add<T>(key, value, DateTime.Now.AddDays(1));      }        public static void Add<T>(string key, T value, TimeSpan slidingExpiration)      {          if (value == null)          {              return;          }            if (slidingExpiration.TotalSeconds <= 0)          {              Remove(key);              return;          }          try          {              if (pool != null)              {                  using (var r = pool.GetClient())                  {                      if (r != null)                      {                          r.SendTimeout = 1000;                          r.Set(key, value, slidingExpiration);                      }                  }              }          }          catch (Exception ex)          {              string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "儲存", key);          }        }        public static T Get<T>(string key)      {          if (string.IsNullOrEmpty(key))          {              return default(T);          }          T obj = default(T);          try          {              if (pool != null)              {                  using (var r = pool.GetClient())                  {                      if (r != null)                      {                          r.SendTimeout = 1000;                          obj = r.Get<T>(key);                      }                  }              }          }          catch (Exception ex)          {              string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "擷取", key);          }          return obj;      }        public static void Remove(string key)      {          try          {              if (pool != null)              {                  using (var r = pool.GetClient())                  {                      if (r != null)                      {                          r.SendTimeout = 1000;                          r.Remove(key);                      }                  }              }          }          catch (Exception ex)          {              string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "刪除", key);          }        }        public static bool Exists(string key)      {          try          {              if (pool != null)              {                  using (var r = pool.GetClient())                  {                      if (r != null)                      {                          r.SendTimeout = 1000;                          return r.ContainsKey(key);                      }                  }              }          }          catch (Exception ex)          {              string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "是否存在", key);          }            return false;      }        public static IDictionary<string, T> GetAll<T>(IEnumerable<string> keys) where T : class      {          if (keys == null)          {              return null;          }          keys = keys.Where(k => !string.IsNullOrWhiteSpace(k));            if (keys.Count() == 1)          {              T obj = Get<T>(keys.Single());                if (obj != null)              {                  return new Dictionary<string, T>() { { keys.Single(), obj } };              }                return null;          }          if (!keys.Any())          {              return null;          }          try          {              using (var r = pool.GetClient())              {                  if (r != null)                  {                      r.SendTimeout = 1000;                      return r.GetAll<T>(keys);                  }              }          }          catch (Exception ex)          {              string msg = string.Format("{0}:{1}發生異常!{2}", "cache", "擷取", keys.Aggregate((a, b) => a + "," + b));          }          return null;      }  }  

  設定配置資訊

 

       這時你就可以

       RedisCacheHelper.Add<string>(key, value);

       這樣調用了。

 

Redis安裝及C#調用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.