>  기사  >  백엔드 개발  >  Windows에서 Redis 캐시 서버를 사용하는 방법

Windows에서 Redis 캐시 서버를 사용하는 방법

高洛峰
高洛峰원래의
2017-02-08 13:53:231321검색

1. Redis 서버


먼저 Redis 서버를 다운로드하고, .msi 버전을 클릭하여 다운로드한 후, Redis 서버를 더블클릭하여 설치하면 설치됩니다. 시스템은 함께 시작됩니다.

Windows에서 Redis 캐시 서버를 사용하는 방법

Redis 서버를 설치한 후 가장 먼저 할 일은 비밀번호를 설정하고 설치 디렉터리를 입력하는 것입니다: C:Program FilesRedis - 찾기 구성 파일: redis.windows-service .conf - 찾기: # requirepass foobared - 입력하고 줄 바꿈 후 추가: requirepass 여기에 새 비밀번호를 입력하세요(앞에 공백 없이 맨 윗줄에 쓰세요) - 서비스로 이동 Redis 서비스를 다시 시작하거나 컴퓨터를 다시 시작하세요

아니요 Ctrip에서 이 사람에게 일어난 일을 보면 비밀번호 설정의 단점을 이해할 수 있습니다. Redis가 공격당한 사건을 기억하세요


2. Redis 클라이언트(명령줄 및 시각화 도구 RDM )

명령줄 데모: Redis 클라이언트 시작, Redis 서버 읽기 및 쓰기

Windows에서 Redis 캐시 서버를 사용하는 방법

위 명령 설명:

cd C: Program FilesRedis: cd 명령은 Redis 설치 디렉터리로 들어갑니다. 이는 Windows 시스템에서 Redis 설치 디렉터리를 두 번 클릭하는 것과 같습니다.

redis-cli.exe: redis-cli 클라이언트 프로그램을 엽니다. 이는 Windows 시스템에서 exe를 두 번 클릭하여 실행하는 것과 같습니다. (위 Redis 서버 프로그램을 설치한 후 클라이언트 프로그램이 필요합니다. 로컬 Redis 서버에 연결하려면 다음 명령을 직접 입력하세요. 원격 서버에 연결하려면 다음과 같이 IP와 포트를 추가해야 합니다. 예: redis-cli.exe -h 111.11 .11.111 -p 6379)


keys *: 모든 키-값 쌍 보기(Redis 서버가 비밀번호를 설정한 경우 이 명령은 오류를 보고하므로 먼저 비밀번호를 입력해야 합니다. , 이 명령을 실행하십시오: 비밀번호 인증)

set blog oppoic.cnblogs.com: 키-값 쌍을 설정하십시오. 키는 blog, 값은 oppoic.cnblogs.com(디렉토리에 저장됨: 디렉토리 이름 설정: 키 값)

get blog: 키 블로그에 해당하는 값 가져오기

keys *: 모든 키-값 쌍 보기

기타 일반적으로 사용되는 명령:

config get dir: redis 설치 디렉터리 가져오기

ping: PONG을 반환하여 redis 서버가 정상임을 나타냅니다.

redis-cli.exe: 첫 번째 데이터베이스 입력( 기본), redis에는 0부터 15까지 총 16개의 라이브러리가 있습니다. 세 번째 라이브러리를 입력하십시오. redis-cli -n 2 (이미 입력되어 있으며 마음대로 전환하려면 0~15를 선택하십시오)

quit: redis 프로그램 종료

exit: dos 창 종료

flushdb: 현재 선택한 데이터베이스의 모든 키 삭제

flushall: 모든 데이터베이스의 데이터베이스 삭제

추가 명령: https://redis.io/commands

이 시점에서 로컬 머신에서 실행되는 Redis 캐시 서버가 설정되었으며 읽고 쓸 수 있습니다. 그러나 명령줄은 분명히 초보 사용자에게 친숙하지 않습니다. 시각화 도구는 Redis Desktop Manager(https://redisdesktop.com/download)

Windows에서 Redis 캐시 서버를 사용하는 방법

트리입니다. 왼쪽에는 이미 연결되어 있음이 표시됩니다. 연결되면 하단의 Redis 서버에 연결을 클릭하여 다른 연결을 추가합니다.

이름: 연결 이름, 부담 없이 선택

호스트: 호스트 주소, 이 머신은 127.0.0.1, 원격으로 입력 해당 IP

포트: 포트, Redis 서버 기본 포트 6379

인증: 비밀번호, 설정된 경우 입력하고 설정하지 않은 경우 공백으로 둡니다

Redis 서버에 접속한 후 보실 수 있으며, 기본값은 16개의 라이브러리(구성 파일은 변경 가능)이며 인덱스는 0부터 시작됩니다. 일반적인 사용법은 하나의 프로젝트와 하나의 라이브러리를 갖는 것이며, 프로젝트 아래의 다양한 기능 모듈은 이 라이브러리 아래의 다른 디렉터리에 저장됩니다.

말할 필요도 없이 시각화 도구를 만든 후의 작업은 더블클릭, 우클릭 생성, 삭제입니다. . . Windows 시스템 사용법을 아는 사람이라면 누구나 이 도구를 사용할 것입니다. 명령줄과 비교할 때 Redis Desktop Manager는 원격 서버의 데이터를 디버깅하는 데 더 사용자 친화적이고 편리한 시각적 도구입니다.

참고: 이 시스템은 원격 서버에 연결하려면 서버의 Redis 설치 디렉터리로 이동하여 redis.windows-service.conf 파일을 찾고 바인드 127.0.0.1을 찾아야 합니다. , 앞에 "#"을 붙여 주석 처리한 다음 서비스를 마우스 오른쪽 버튼으로 클릭하여 Redis 서비스를 다시 시작하거나 Windows 시스템을 다시 시작하세요.

3. 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;
        }
    }
}

키 이름과 값 wangjie가 있는 레코드를 Redis 서버의 첫 번째 라이브러리의 fd1 디렉터리에 추가합니다.

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的记录不存在");
}

두 번째 라이브러리의 fd2 디렉토리로 이동합니다. redis 서버, 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에 코드를 복사해서 직접 컴파일해서 실행해보세요


4. 기타

MSOpenTech에서 개발한 Redis 캐시 서버는 쓰기 후 컴퓨터를 다시 시작해도 키-값 쌍이 여전히 존재합니다. 일반적으로 키 쓰기 시 만료 시간을 설정해야 합니다. 값 쌍이 없으면 점유된 메모리가 해제되지 않습니다. Redis 저장 방법에는 문자열에 해당하는 키가 있을 뿐만 아니라 List, HashTable 등에 해당하는 키도 있습니다. 물론 Redis의 고급 사용은 여전히 ​​Linux에서 사용됩니다.

Windows에서 Redis 캐시 서버 사용과 관련된 더 많은 글은 PHP 중국어 홈페이지를 참고해주세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.