首頁  >  文章  >  後端開發  >  Redis快取伺服器在Windows下的使用

Redis快取伺服器在Windows下的使用

高洛峰
高洛峰原創
2017-02-08 13:53:231321瀏覽

一、Redis服務端


先下載Redis伺服器,點擊前往下載.msi版本,雙擊安裝Redis服務端就有了,並以服務的形式隨系統一起啟動:

Redis快取伺服器在Windows下的使用

安裝好Redis伺服器之後第一件事就是設定密碼,進入安裝目錄:C:Program FilesRedis - 找到設定檔:redis.windows-service.conf - 找到:# requirepass foobared - 回車換行加上:requirepass 這裡寫自己的新密碼(頂行寫,前面不要留空格) - 到服務裡重啟Redis服務,或是重啟電腦

不設定密碼的壞處,看看攜程這哥們的遭遇就知道了:記一次Redis被攻擊的事件


二、Redis客戶端(命令列與視覺化工具RDM)

命令列方式示範:啟動Redis客戶端、讀取與寫入Redis伺服器

Redis快取伺服器在Windows下的使用

上圖指令解釋:

:命令進入Redis安裝目錄,相當於Windows系統裡雙擊進入Redis的安裝目錄

redis-cli.exe:打開redis-cli客戶端程序,相當於Windows系統裡雙擊運行一個exe程序(安裝了上面的Redis服務端程序,需要一個客戶端程式連接這個服務端。

keys *:查看所有鍵值對(如果Redis伺服器設定了密碼,這條指令會報錯,需要先輸入密碼,執行此指令:auth 你的密碼)

set blog oppoic.cnblogs.com:設定一個鍵值對,鍵是:blog,值是:oppoic.cnblogs.com(按目錄儲存:set 目錄名稱:鍵值)

get blog:取得鍵為blog對應的值

keys *:查看所有鍵值對

其他常用指令:

config get dir:取得redis安裝目錄

ping:回傳PONG表示redis伺服器正常

redis-cli.exe:進入第一個資料庫(預設),redis共0到15共16個庫,進入第三個庫redis-cli -n 2(已經進去了,select 0~15 隨意切換)

quit:退出redis程式

exit:退出dos視窗

flushdb:刪除目前選擇資料庫中的所有key

flushall:刪除所有資料庫中的資料庫

更多命令:https://redis.io/commands

至此,一個運行在本機的Redis快取伺服器已經搭建完成,並且可以讀寫了。但命令列顯然對小白用戶不友好,視覺化工具登場:Redis Desktop Manager(https://redisdesktop.com/download)

左側樹顯示已經有一個連接了,點擊底部的Connect to Redis Server再增加一個連線:Redis快取伺服器在Windows下的使用

Name:連線名稱,隨便起

Host:主機位址,本機就是127.0.0.1,遠端的輸入對應IP

Port:端口,Redis伺服器預設連接埠6379

Auth:密碼,設定了就輸,沒設定留空

連上Redis伺服器就可以看到,預設16個函式庫(設定檔可改),索引從0開始。常見用法是一個專案一個庫,專案下不同功能模組分不同目錄存在這個庫下。

有了視覺化工具之後的操作就不用說了,雙擊,右鍵新建、刪除。 。 。會用Windows系統的都會用這個工具。相較於命令列,Redis Desktop Manager這個視覺化工具更友好,調試遠端伺服器上的資料也更方便,指哪打哪。

註:本機可以這樣,連接遠端伺服器需要到伺服器上的Redis安裝目錄下,找到redis.windows-service.conf文件,找到bind 127.0.0.1 前面加"#"註解掉,然後到服務裡右鍵重新啟動redis服務,或重新啟動Windows系統

三、C#操作Redis伺服器

以上都是命令列和視覺化工具操作Redis伺服器,C#程式操作Redis需要藉助StackExchange.Redis(https://github.com/StackExchange/StackExchange.Redis),為了統一調用,封裝了一個RedisHelper幫助類別:

using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.ComponentModel;
using System.Configuration;
using System.Reflection;
using System.Text;

namespace redis_Demo
{
    /// <summary>
    /// Redis 帮助类
    /// </summary>
    public static class RedisHelper
    {
        private static string _conn = ConfigurationManager.AppSettings["redis_connection_string"] ?? "127.0.0.1:6379";
        private static string _pwd = ConfigurationManager.AppSettings["redis_connection_pwd"] ?? "123456";

        static ConnectionMultiplexer _redis;
        static readonly object _locker = new object();

        #region 单例模式
        public static ConnectionMultiplexer Manager
        {
            get
            {
                if (_redis == null)
                {
                    lock (_locker)
                    {
                        if (_redis != null) return _redis;

                        _redis = GetManager();
                        return _redis;
                    }
                }
                return _redis;
            }
        }

        private static ConnectionMultiplexer GetManager(string connectionString = null)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                connectionString = _conn;
            }
            var options = ConfigurationOptions.Parse(connectionString);
            options.Password = _pwd;
            return ConnectionMultiplexer.Connect(options);
        }
        #endregion

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="folder">目录</param>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expireMinutes">过期时间,单位:分钟。默认600分钟</param>
        /// <param name="db">库,默认第一个。0~15共16个库</param>
        /// <returns></returns>
        public static bool StringSet(CacheFolderEnum folder, string key, string value, int expireMinutes = 600, int db = -1)
        {
            string fd = GetDescription(folder);
            return Manager.GetDatabase(db).StringSet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, value, TimeSpan.FromMinutes(expireMinutes));
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="folder">目录</param>
        /// <param name="key">键</param>
        /// <param name="db">库,默认第一个。0~15共16个库</param>
        /// <returns></returns>
        public static string StringGet(CacheFolderEnum folder, string key, int db = -1)
        {
            try
            {
                string fd = GetDescription(folder);
                return Manager.GetDatabase(db).StringGet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="folder">目录</param>
        /// <param name="key">键</param>
        /// <param name="db">库,默认第一个。0~15共16个库</param>
        /// <returns></returns>
        public static bool StringRemove(CacheFolderEnum folder, string key, int db = -1)
        {
            try
            {
                string fd = GetDescription(folder);
                return Manager.GetDatabase(db).KeyDelete(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="db">库,默认第一个。0~15共16个库</param>
        public static bool KeyExists(CacheFolderEnum folder, string key, int db = -1)
        {
            try
            {
                string fd = GetDescription(folder);
                return Manager.GetDatabase(db).KeyExists(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 延期
        /// </summary>
        /// <param name="folder">目录</param>
        /// <param name="key">键</param>
        /// <param name="min">延长时间,单位:分钟,默认600分钟</param>
        /// <param name="db">库,默认第一个。0~15共16个库</param>
        public static bool AddExpire(CacheFolderEnum folder, string key, int min = 600, int db = -1)
        {
            try
            {
                string fd = GetDescription(folder);
                return Manager.GetDatabase(db).KeyExpire(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, DateTime.Now.AddMinutes(min));
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 添加实体
        /// </summary>
        /// <param name="folder">目录</param>
        /// <param name="key">键</param>
        /// <param name="t">实体</param>
        /// <param name="ts">延长时间,单位:分钟,默认600分钟</param>
        /// <param name="db">库,默认第一个。0~15共16个库</param>
        public static bool Set<T>(CacheFolderEnum folder, string key, T t, int expireMinutes = 600, int db = -1)
        {
            string fd = GetDescription(folder);
            var str = JsonConvert.SerializeObject(t);
            return Manager.GetDatabase(db).StringSet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key, str, TimeSpan.FromMinutes(expireMinutes));
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="folder">目录</param>
        /// <param name="key">键</param>
        /// <param name="db">库,默认第一个。0~15共16个库</param>
        public static T Get<T>(CacheFolderEnum folder, string key, int db = -1) where T : class
        {
            string fd = GetDescription(folder);
            var strValue = Manager.GetDatabase(db).StringGet(string.IsNullOrEmpty(fd) ? key : fd + ":" + key);
            return string.IsNullOrEmpty(strValue) ? null : JsonConvert.DeserializeObject<T>(strValue);
        }

        /// <summary>
        /// 获得枚举的Description
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
        /// <returns>枚举的Description</returns>
        private static string GetDescription(this Enum value, Boolean nameInstead = true)
        {
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name == null)
            {
                return null;
            }

            FieldInfo field = type.GetField(name);
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;

            if (attribute == null && nameInstead == true)
            {
                return name;
            }
            return attribute == null ? null : attribute.Description;
        }
    }
}

向redis伺服器第一個庫的fd1目錄裡,添加一個鍵為name,值為wangjie的記錄:

RedisHelper.StringSet(CacheFolderEnum.Folder1, "name", "wangjie");

取得這條記錄:

string key = RedisHelper.StringGet(CacheFolderEnum.Folder1, "name");
Console.WriteLine("键为name的记录对应的值:" + key);

刪除這條記錄:

bool result = RedisHelper.StringRemove(CacheFolderEnum.Folder1, "name");
if (result)
{
    Console.WriteLine("键为name的记录删除成功");
}
else
{
    Console.WriteLine("键为name的记录删除失败");
}

查詢這條記錄是否存在:

bool ifExist = RedisHelper.KeyExists(CacheFolderEnum.Folder1, "name");
if (ifExist)
{
    Console.WriteLine("键为name的记录存在");
}
else
{
    Console.WriteLine("键为name的记录不存在");
}

向redis伺服器第二個函式庫的fd2目錄裡,加上一個鍵為sd1,值為一個物件的記錄:

Student student = new Student() { Id = 1, Name = "张三", Class = "三年二班" };
RedisHelper.Set<Student>(CacheFolderEnum.Folder2, "sd1", student, 10, 1);

取得這個物件:

Student sdGet = RedisHelper.Get<Student>(CacheFolderEnum.Folder2, "sd1", 1);
if (sdGet != null)
{
    Console.WriteLine("Id:" + sdGet.Id + " Name:" + sdGet.Name + " Class:" + sdGet.Class);
}
else
{
    Console.WriteLine("找不到键为sd1的记录");
}

源碼: (http://files.cnblogs.com/files/oppoic/redis_Demo.zip)

環境是VS 2013,如果跑不起來自行把cs裡的程式碼拷出編譯運行


四、其他

四、其他

🎜四、其他🎜 MSOpenTech開發Redis快取伺服器自帶持久化,寫入之後重啟電腦鍵值對還存在,一般寫入鍵值對要設定過期時間,否則一直佔用記憶體不會被釋放。 Redis儲存方式不光有鍵對應字串,還有對應List,HashTable等,當然Redis更多高階的用法還是在Linux下。 🎜🎜更多Redis快取伺服器在Windows下的使用相關文章請關注PHP中文網! 🎜
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn