How to use Redis cache server under Windows
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:
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
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)
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

DeepSeek is a powerful intelligent search and analysis tool that provides two access methods: web version and official website. The web version is convenient and efficient, and can be used without installation; the official website provides comprehensive product information, download resources and support services. Whether individuals or corporate users, they can easily obtain and analyze massive data through DeepSeek to improve work efficiency, assist decision-making and promote innovation.

The way to update ByBit exchanges varies by platform and device: Mobile: Check for updates and install in the app store. Desktop Client: Check for updates in the Help menu and install automatically. Web page: You need to manually access the official website for updates. Failure to update the exchange can lead to security vulnerabilities, functional limitations, compatibility issues and reduced transaction execution efficiency.

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

There are many ways to install DeepSeek, including: compile from source (for experienced developers) using precompiled packages (for Windows users) using Docker containers (for most convenient, no need to worry about compatibility) No matter which method you choose, Please read the official documents carefully and prepare them fully to avoid unnecessary trouble.

The official website entrance of the Coinsuper Exchange: https://www.coinsuper.com. The client download channels are: Windows client, macOS client, and mobile (iOS/Android). Registration requires an email, mobile phone number and password, and you need to complete real-name authentication before you can trade. The platform provides a variety of digital asset transactions, including Bitcoin, Ethereum, etc., with the transaction fee rate of 0.1% for both orders and acceptors. Security safeguards include cold wallet storage, dual-factor verification, anti-money laundering and anti-terrorism financing measures, and with security public

BITGet is a cryptocurrency exchange that provides a variety of trading services including spot trading, contract trading and derivatives. Founded in 2018, the exchange is headquartered in Singapore and is committed to providing users with a safe and reliable trading platform. BITGet offers a variety of trading pairs, including BTC/USDT, ETH/USDT and XRP/USDT. Additionally, the exchange has a reputation for security and liquidity and offers a variety of features such as premium order types, leveraged trading and 24/7 customer support.

Ouyi OKX, the world's leading digital asset exchange, has now launched an official installation package to provide a safe and convenient trading experience. The OKX installation package of Ouyi does not need to be accessed through a browser. It can directly install independent applications on the device, creating a stable and efficient trading platform for users. The installation process is simple and easy to understand. Users only need to download the latest version of the installation package and follow the prompts to complete the installation step by step.

Gate.io is a popular cryptocurrency exchange that users can use by downloading its installation package and installing it on their devices. The steps to obtain the installation package are as follows: Visit the official website of Gate.io, click "Download", select the corresponding operating system (Windows, Mac or Linux), and download the installation package to your computer. It is recommended to temporarily disable antivirus software or firewall during installation to ensure smooth installation. After completion, the user needs to create a Gate.io account to start using it.
