search
HomeBackend DevelopmentPHP TutorialHow to use Redis cache server under Windows
How to use Redis cache server under WindowsFeb 08, 2017 pm 01:53 PM
rediswindows

1. Redis server


First download the Redis server, click to download the .msi version, double-click to install the Redis server, and it will be installed as a service. Start the system together:

How to use Redis cache server under Windows

The first thing after installing the Redis server is to set a password and enter the installation directory: C:\Program Files\Redis - Find the configuration file: redis. windows-service.conf - Find: # requirepass foobared - Enter, line feed and add: requirepass Write your new password here (write it on the top line, without leaving a space in front) - Go to the service and restart the Redis service, or restart the computer

The disadvantages of not setting a password can be understood by looking at what happened to this guy from Ctrip: Remember an incident where Redis was attacked


2. Redis client (command line and Visual tool RDM)

Command line demonstration: start Redis client, read and write Redis server

How to use Redis cache server under Windows

Command explanation in the above picture:

cd C:\Program Files\Redis: The cd command enters the Redis installation directory, which is equivalent to double-clicking to enter the Redis installation directory in Windows.

redis-cli.exe: Opens the redis-cli client program, which is equivalent to Windows Double-click to run an exe program in the system (after installing the above Redis server program, a client program is needed to connect to the server. To connect to the local redis server, type this command directly. To connect to the remote, you need to add the ip and port, for example: redis- cli.exe -h 111.11.11.111 -p 6379)


keys *: View all key-value pairs (if the Redis server has a password set, this command will report an error, need Enter the password first and execute this command: auth your password)

set blog oppoic.cnblogs.com: Set a key-value pair, the key is: blog, the value is: oppoic.cnblogs.com (stored by directory : set directory name: key value)

get blog: Get the value corresponding to the key blog

keys *: View all key-value pairs

Other commonly used commands:

config get dir: Get the redis installation directory

ping: Return PONG to indicate that the redis server is normal

redis-cli.exe: Enter the first database (default), redis has a total of 0 There are 16 libraries in total to 15, enter the third library redis-cli -n 2 (already entered, select 0~15 to switch at will)

quit: Exit the redis program

exit: Exit dos window

flushdb: Delete all keys in the currently selected database

flushall: Delete databases in all databases

More commands: https://redis.io/ commands

At this point, a Redis cache server running on the local machine has been set up and can be read and written. However, the command line is obviously not friendly to novice users. The visualization tool appears: Redis Desktop Manager (https://redisdesktop.com/download)

How to use Redis cache server under Windows

The tree on the left shows that there are already Once connected, click Connect to Redis Server at the bottom to add another connection:

Name: connection name, start as you like

Host: host address, this machine is 127.0.0.1, input remotely Corresponding IP

Port: Port, the Redis server default port is 6379

Auth: password, enter it if set, leave it blank if not set

You can see it after connecting to the Redis server , the default is 16 libraries (the configuration file can be changed), and the index starts from 0. A common usage is to have one project and one library, and different functional modules under the project are stored in different directories under this library.

Needless to say, the operation after having the visualization tool is to double-click, right-click to create, and delete. . . Anyone who knows how to use Windows system will use this tool. Compared with the command line, Redis Desktop Manager is a visual tool that is more user-friendly and more convenient for debugging data on remote servers.

Note: This machine can do this. To connect to the remote server, you need to go to the Redis installation directory on the server, find the redis.windows-service.conf file, find bind 127.0.0.1, add "#" in front of it, comment it out, and then Right-click on the service to restart the redis service, or restart the Windows system

3. C# operating Redis server

The above are all command lines and visual tools to operate Redis server. C# programs need to use StackExchange.Redis(https://github.com/StackExchange/StackExchange.Redis to operate Redis) ), in order to call it uniformly, a RedisHelper helper class is encapsulated:

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

Add a record with the key name and the value wangjie to the fd1 directory of the first library of the redis server:

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

Get this record:

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

Delete this record:

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

Query whether this record exists:

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

Go to the fd2 directory of the second library of the redis server , add a record with the key sd1 and the value an object:

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

Get this object:

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

Source code: (http://files.cnblogs.com/files/oppoic/redis_Demo .zip)

The environment is VS 2013. If it cannot run, copy the code in cs and compile and run it yourself


4. Others

MSOpenTech developed the Redis cache server with built-in persistence. After writing, the key-value pair will still exist when the computer is restarted. Generally, the expiration time must be set for writing the key-value pair, otherwise the memory occupied will not be released. Redis storage method not only has keys corresponding to strings, but also corresponds to List, HashTable, etc. Of course, more advanced uses of Redis are still under Linux.

For more articles related to the use of Redis cache server under Windows, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
c盘的users是什么文件夹?可以删除吗?c盘的users是什么文件夹?可以删除吗?Nov 10, 2022 pm 06:20 PM

c盘的users是用户文件夹,主要存放用户的各项配置文件。users文件夹是windows系统的重要文件夹,不能随意删除;它保存了很多用户信息,一旦删除会造成数据丢失,严重的话会导致系统无法启动。

启动任务管理器的三个快捷键是什么启动任务管理器的三个快捷键是什么Sep 21, 2022 pm 02:47 PM

启动任务管理器的三个快捷键是:1、“Ctrl+Shift+Esc”,可直接打开任务管理器;2、“Ctrl+Alt+Delete”,会进入“安全选项”的锁定界面,选择“任务管理器”,即可以打开任务管理器;3、“Win+R”,会打开“运行”窗口,输入“taskmgr”命令,点击“确定”即可调出任务管理器。

window下报错“php不是内部或外部命令”怎么解决window下报错“php不是内部或外部命令”怎么解决Mar 23, 2023 pm 02:11 PM

对于刚刚开始使用PHP的用户来说,如果在Windows操作系统中遇到了“php不是内部或外部命令”的问题,可能会感到困惑。这个错误通常是由于系统无法识别PHP的路径导致的。在本文中,我将为您提供一些可能会导致这个问题的原因和解决方法,以帮助您快速解决这个问题。

微软的pin码是什么微软的pin码是什么Oct 14, 2022 pm 03:16 PM

PIN码是Windows系统为了方便用户本地登录而独立于window账户密码的快捷登录密码,是Windows系统新添加的一套本地密码策略;在用户登陆了Microsoft账户后就可以设置PIN来代替账户密码,不仅提高安全性,而且也可以让很多和账户相关的操作变得更加方便。PIN码只能通过本机登录,无法远程使用,所以不用担心PIN码被盗。

win10自带的onenote是啥版本win10自带的onenote是啥版本Sep 09, 2022 am 10:56 AM

win10自带的onenote是UWP版本;onenote是一套用于自由形式的信息获取以及多用户协作工具,而UWP版本是“Universal Windows Platform”的简称,表示windows通用应用平台,不是为特定的终端设计的,而是针对使用windows系统的各种平台。

win10为什么没有“扫雷”游戏了win10为什么没有“扫雷”游戏了Aug 17, 2022 pm 03:37 PM

因为win10系统是不自带扫雷游戏的,需要用户自行手动安装。安装步骤:1、点击打开“开始菜单”;2、在打开的菜单中,找到“Microsoft Store”应用商店,并点击进入;3、在应用商店主页的搜索框中,搜索“minesweeper”;4、在搜索结果中,点击选择需要下载的“扫雷”游戏;5、点击“获取”按钮,等待获取完毕后自动完成安装游戏即可。

在windows中鼠标指针呈四箭头时一般表示什么在windows中鼠标指针呈四箭头时一般表示什么Dec 17, 2020 am 11:39 AM

在windows中鼠标指针呈四箭头时一般表示选中对象可以上、下、左、右移动。在Windows中鼠标指针首次用不同的指针来表示不同的状态,如系统忙、移动中、拖放中;在Windows中使用的鼠标指针文件还被称为“光标文件”或“动态光标文件”。

windows操作系统的特点包括什么windows操作系统的特点包括什么Sep 28, 2020 pm 12:02 PM

windows操作系统的特点包括:1、图形界面;直观高效的面向对象的图形用户界面,易学易用。2、多任务;允许用户同时运行多个应用程序,或在一个程序中同时做几件事情。3、即插即用。4、出色的多媒体功能。5、对内存的自动化管理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.