Table of Contents
Execute a single command
In the daily online development process, sometimes it is inevitable to manually create data and import it into Redis. Normally we would write a script to do this. But there is another more convenient way, which is to directly use redis-cli to execute a series of instructions in batches.
If a string has multiple lines and you want to pass it into the set command, how does redis-cli do it? You can use the -x option, which uses the contents of standard input as the last argument.
redis-cli also supports repeated execution of instructions multiple times. Set an interval between the execution of each instruction, so that you can observe the output content of a certain instruction over time. Variety.
Although the entire Redis database cannot be exported to CSV format alone, a single item can be exported. The results of the command are in CSV format.
In the lua script section, we use the eval instruction to execute the script string. Each time, we compress the script content into a single-line string and then call the eval instruction, which is very cumbersome. , and the readability is very poor. redis-cli takes this into account and can execute script files directly.
We can use the --stat parameter to monitor the status of the server in real time, and output it in real time every 1s.
This function is so practical, I have tried it online countless times. Every time you encounter the problem of occasional lag in Redis, the first thing that comes to mind is whether there is a large KEY in the instance. The memory expansion and release of the large KEY will cause the main thread to lag. If you know whether there is a big KEY inside, you can write a program to scan it yourself, but this is too cumbersome. redis-cli provides the --bigkeys parameter to quickly scan out the large KEYs in the memory. Use the -i parameter to control the scan interval to avoid the scan command causing a sudden increase in the server's ops alarm.
There is a Redis server online now whose OPS is too high. Many business modules are using this Redis. How can we determine which business is causing the abnormally high OPS? . At this time, you can sample the instructions of the online server. By observing the sampled instructions, you can roughly analyze the business points with a high proportion of OPS. Use the monitor command to display all instructions executed by the server at once. It should be noted that when using it, even if you want to force a break, you must press Ctrl C, otherwise too many instructions will appear on the display, which will be dazzling and crackling in an instant.
诊断服务器时延
远程 rdb 备份
模拟从库
Home Database Redis How to use the Redis command line tool

How to use the Redis command line tool

Jun 03, 2023 am 08:53 AM
redis

Execute a single command

Usually when accessing the Redis server, we usually use redis-cli to enter the interactive mode, and then read and write the server by asking and answering. In this case, we use its "interactive" model". There is another "direct mode", which executes the command and obtains the output results by passing the command parameters directly to redis-cli.

$ redis-cli incrby foo 5<br/>(integer) 5<br/>$ redis-cli incrby foo 5<br/>(integer) 10<br/>
Copy after login


If the output content is large, you can also redirect the output to an external file

$ redis-cli info > info.txt<br/>$ wc -l info.txt<br/>     120 info.txt<br/>
Copy after login


The server pointed to by the above command is the default server address. If you want to point A specific server can execute commands in batches like this

// -n 2 表示使用第2个库,相当于 select 2<br/>$ redis-cli -h localhost -p 6379 -n 2 ping<br/>PONG<br/>
Copy after login

In the daily online development process, sometimes it is inevitable to manually create data and import it into Redis. Normally we would write a script to do this. But there is another more convenient way, which is to directly use redis-cli to execute a series of instructions in batches.

$ cat cmds.txt<br/>set foo1 bar1<br/>set foo2 bar2<br/>set foo3 bar3<br/>......<br/>$ cat cmds.txt | redis-cli<br/>OK<br/>OK<br/>OK<br/>...<br/>
Copy after login

The above command uses a Unix pipe to connect the standard output of the cat command to the standard input of redis-cli. In fact, you can also directly use input redirection to execute instructions in batches.

$ redis-cli < cmds.txt<br/>OK<br/>OK<br/>OK<br/>...<br/>
Copy after login

set multi-line string

If a string has multiple lines and you want to pass it into the set command, how does redis-cli do it? You can use the -x option, which uses the contents of standard input as the last argument.

$ cat str.txt<br/>Ernest Hemingway once wrote,<br/>"The world is a fine place and worth fighting for."<br/>I agree with the second part.<br/>$ redis-cli -x set foo < str.txt<br/>OK<br/>$ redis-cli get foo<br/>"Ernest Hemingway once wrote,\n\"The world is a fine place and worth fighting for.\"\nI agree with the second part.\n"<br/>
Copy after login

Repeat execution of instructions

redis-cli also supports repeated execution of instructions multiple times. Set an interval between the execution of each instruction, so that you can observe the output content of a certain instruction over time. Variety.

// 间隔1s,执行5次,观察qps的变化<br/>$ redis-cli -r 5 -i 1 info | grep ops<br/>instantaneous_ops_per_sec:43469<br/>instantaneous_ops_per_sec:47460<br/>instantaneous_ops_per_sec:47699<br/>instantaneous_ops_per_sec:46434<br/>instantaneous_ops_per_sec:47216<br/>
Copy after login

If the number of times is set to -1, it will be repeated countless times and executed forever. If the -i parameter is not provided, there will be no interval and the execution will be repeated continuously. In interactive mode, you can also execute instructions repeatedly. The form is rather weird. Add the number of times in front of the instruction.

127.0.0.1:6379> 5 ping<br/>PONG<br/>PONG<br/>PONG<br/>PONG<br/>PONG<br/># 下面的指令很可怕,你的屏幕要愤怒了<br/>127.0.0.1:6379> 10000 info<br/>.......<br/>
Copy after login

Export csv

Although the entire Redis database cannot be exported to CSV format alone, a single item can be exported. The results of the command are in CSV format.

$ redis-cli rpush lfoo a b c d e f g<br/>(integer) 7<br/>$ redis-cli --csv lrange lfoo 0 -1<br/>"a","b","c","d","e","f","g"<br/>$ redis-cli hmset hfoo a 1 b 2 c 3 d 4<br/>OK<br/>$ redis-cli --csv hgetall hfoo<br/>"a","1","b","2","c","3","d","4"<br/>
Copy after login

Of course, this export function is relatively weak, it is just a bunch of strings separated by commas. However, you can combine the batch execution of commands to see the export effect of multiple instructions.

$ redis-cli --csv -r 5 hgetall hfoo<br/>"a","1","b","2","c","3","d","4"<br/>"a","1","b","2","c","3","d","4"<br/>"a","1","b","2","c","3","d","4"<br/>"a","1","b","2","c","3","d","4"<br/>"a","1","b","2","c","3","d","4"<br/>
Copy after login

After seeing this, readers should understand that the effect of the --csv parameter is to convert the output once and separate it with commas, nothing more.


Execute lua script

In the lua script section, we use the eval instruction to execute the script string. Each time, we compress the script content into a single-line string and then call the eval instruction, which is very cumbersome. , and the readability is very poor. redis-cli takes this into account and can execute script files directly.

127.0.0.1:6379> eval "return redis.pcall(&#39;mset&#39;, KEYS[1], ARGV[1], KEYS[2], ARGV[2])" 2 foo1 foo2 bar1 bar2<br/>OK<br/>127.0.0.1:6379> eval "return redis.pcall(&#39;mget&#39;, KEYS[1], KEYS[2])" 2 foo1 foo2<br/>1) "bar1"<br/>2) "bar2"<br/>
Copy after login

Below we execute the above instructions in the form of a script. The parameter format is different. KEY and ARGV need to be separated by commas, and there is no need to provide the number of KEY parameters

$ cat mset.txt<br/>return redis.pcall(&#39;mset&#39;, KEYS[1], ARGV[1], KEYS[2], ARGV[2])<br/>$ cat mget.txt<br/>return redis.pcall(&#39;mget&#39;, KEYS[1], KEYS[2])<br/>$ redis-cli --eval mset.txt foo1 foo2 , bar1 bar2<br/>OK<br/>$ redis-cli --eval mget.txt foo1 foo2<br/>1) "bar1"<br/>2) "bar2"<br/>
Copy after login

If your lua script is too long, --eval will be useful.


Monitor server status

We can use the --stat parameter to monitor the status of the server in real time, and output it in real time every 1s.

$ redis-cli --stat<br/>------- data ------ --------------------- load -------------------- - child -<br/>keys       mem      clients blocked requests            connections<br/>2          6.66M    100     0       11591628 (+0)       335<br/>2          6.66M    100     0       11653169 (+61541)   335<br/>2          6.66M    100     0       11706550 (+53381)   335<br/>2          6.54M    100     0       11758831 (+52281)   335<br/>2          6.66M    100     0       11803132 (+44301)   335<br/>2          6.66M    100     0       11854183 (+51051)   335<br/>
Copy after login

If you think the interval is too long or too short, you can use the -i parameter to adjust the output interval.


Scan large KEY

This function is so practical, I have tried it online countless times. Every time you encounter the problem of occasional lag in Redis, the first thing that comes to mind is whether there is a large KEY in the instance. The memory expansion and release of the large KEY will cause the main thread to lag. If you know whether there is a big KEY inside, you can write a program to scan it yourself, but this is too cumbersome. redis-cli provides the --bigkeys parameter to quickly scan out the large KEYs in the memory. Use the -i parameter to control the scan interval to avoid the scan command causing a sudden increase in the server's ops alarm.

$ ./redis-cli --bigkeys -i 0.01<br/># Scanning the entire keyspace to find biggest keys as well as<br/># average sizes per key type.  You can use -i 0.1 to sleep 0.1 sec<br/># per 100 SCAN commands (not usually needed).<br/><br/>[00.00%] Biggest zset   found so far &#39;hist:aht:main:async_finish:20180425:17&#39; with 1440 members<br/>[00.00%] Biggest zset   found so far &#39;hist:qps:async:authorize:20170311:27&#39; with 2465 members<br/>[00.00%] Biggest hash   found so far &#39;job:counters:6ya9ypu6ckcl&#39; with 3 fields<br/>[00.01%] Biggest string found so far &#39;rt:aht:main:device_online:68:{-4}&#39; with 4 bytes<br/>[00.01%] Biggest zset   found so far &#39;machine:load:20180709&#39; with 2879 members<br/>[00.02%] Biggest string found so far &#39;6y6fze8kj7cy:{-7}&#39; with 90 bytes<br/>
Copy after login

redis-cli will record the KEY with the largest length for each object type. For each object type, refreshing the highest record will immediately output it. It can guarantee the output of KEYs with a length of Top1, but there is no guarantee that KEYs such as Top2 and Top3 can be scanned out. A common approach is to perform multiple scans, or to remove the highest priority keyword and then scan again to determine if there are still lower priority keywords.


Sampling Server Instructions

There is a Redis server online now whose OPS is too high. Many business modules are using this Redis. How can we determine which business is causing the abnormally high OPS? . At this time, you can sample the instructions of the online server. By observing the sampled instructions, you can roughly analyze the business points with a high proportion of OPS. Use the monitor command to display all instructions executed by the server at once. It should be noted that when using it, even if you want to force a break, you must press Ctrl C, otherwise too many instructions will appear on the display, which will be dazzling and crackling in an instant.

$ redis-cli --host 192.168.x.x --port 6379 monitor<br/>1539853410.458483 [0 10.100.90.62:34365] "GET" "6yax3eb6etq8:{-7}"<br/>1539853410.459212 [0 10.100.90.61:56659] "PFADD" "growth:dau:20181018" "2klxkimass8w"<br/>1539853410.462938 [0 10.100.90.62:20681] "GET" "6yax3eb6etq8:{-7}"<br/>1539853410.467231 [0 10.100.90.61:40277] "PFADD" "growth:dau:20181018" "2kei0to86ps1"<br/>1539853410.470319 [0 10.100.90.62:34365] "GET" "6yax3eb6etq8:{-7}"<br/>1539853410.473927 [0 10.100.90.61:58128] "GET" "6yax3eb6etq8:{-7}"<br/>1539853410.475712 [0 10.100.90.61:40277] "PFADD" "growth:dau:20181018" "2km8sqhlefpc"<br/>1539853410.477053 [0 10.100.90.62:61292] "GET" "6yax3eb6etq8:{-7}"<br/>
Copy after login

诊断服务器时延

通常我们使用Unix的ping命令来测量两台计算机的延迟。Redis 也提供了时延诊断指令,不过它的原理不太一样,它是诊断当前机器和 Redis 服务器之间的指令(PING指令)时延,它不仅仅是物理网络的时延,还和当前的 Redis 主线程是否忙碌有关。如果你发现 Unix 的 ping 指令时延很小,而 Redis 的时延很大,那说明 Redis 服务器在执行指令时有微弱卡顿。

$ redis-cli --host 192.168.x.x --port 6379 --latency<br/>min: 0, max: 5, avg: 0.08 (305 samples)<br/>
Copy after login


时延单位是 ms。redis-cli 还能显示时延的分布情况,而且是图形化输出。

$ redis-cli --latency-dist<br/>
Copy after login


这个图形的含义作者没有描述,读者们可以尝试破解一下。

远程 rdb 备份

执行下面的命令就可以将远程的 Redis 实例备份到本地机器,远程服务器会执行一次bgsave操作,然后将 rdb 文件传输到客户端。远程 rdb 备份让我们有一种“秀才不出门,全知天下事”的感觉。

$ ./redis-cli --host 192.168.x.x --port 6379 --rdb ./user.rdb<br/>SYNC sent to master, writing 2501265095 bytes to &#39;./user.rdb&#39;<br/>Transfer finished with success.<br/>
Copy after login

模拟从库

如果你想观察主从服务器之间都同步了那些数据,可以使用 redis-cli 模拟从库。

$ ./redis-cli --host 192.168.x.x --port 6379 --slave<br/>SYNC with master, discarding 51778306 bytes of bulk transfer...<br/>SYNC done. Logging commands from master.<br/>...<br/>
Copy after login


从库连上主库的第一件事是全量同步,所以看到上面的指令卡顿这很正常,待首次全量同步完成后,就会输出增量的 aof 日志。

The above is the detailed content of How to use the Redis command line tool. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution to 0x80242008 error when installing Windows 11 10.0.22000.100 Solution to 0x80242008 error when installing Windows 11 10.0.22000.100 May 08, 2024 pm 03:50 PM

1. Start the [Start] menu, enter [cmd], right-click [Command Prompt], and select Run as [Administrator]. 2. Enter the following commands in sequence (copy and paste carefully): SCconfigwuauservstart=auto, press Enter SCconfigbitsstart=auto, press Enter SCconfigcryptsvcstart=auto, press Enter SCconfigtrustedinstallerstart=auto, press Enter SCconfigwuauservtype=share, press Enter netstopwuauserv , press enter netstopcryptS

Golang API caching strategy and optimization Golang API caching strategy and optimization May 07, 2024 pm 02:12 PM

The caching strategy in GolangAPI can improve performance and reduce server load. Commonly used strategies are: LRU, LFU, FIFO and TTL. Optimization techniques include selecting appropriate cache storage, hierarchical caching, invalidation management, and monitoring and tuning. In the practical case, the LRU cache is used to optimize the API for obtaining user information from the database. The data can be quickly retrieved from the cache. Otherwise, the cache can be updated after obtaining it from the database.

Caching mechanism and application practice in PHP development Caching mechanism and application practice in PHP development May 09, 2024 pm 01:30 PM

In PHP development, the caching mechanism improves performance by temporarily storing frequently accessed data in memory or disk, thereby reducing the number of database accesses. Cache types mainly include memory, file and database cache. Caching can be implemented in PHP using built-in functions or third-party libraries, such as cache_get() and Memcache. Common practical applications include caching database query results to optimize query performance and caching page output to speed up rendering. The caching mechanism effectively improves website response speed, enhances user experience and reduces server load.

How to upgrade Win11 English 21996 to Simplified Chinese 22000_How to upgrade Win11 English 21996 to Simplified Chinese 22000 How to upgrade Win11 English 21996 to Simplified Chinese 22000_How to upgrade Win11 English 21996 to Simplified Chinese 22000 May 08, 2024 pm 05:10 PM

First you need to set the system language to Simplified Chinese display and restart. Of course, if you have changed the display language to Simplified Chinese before, you can just skip this step. Next, start operating the registry, regedit.exe, directly navigate to HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlNlsLanguage in the left navigation bar or the upper address bar, and then modify the InstallLanguage key value and Default key value to 0804 (if you want to change it to English en-us, you need First set the system display language to en-us, restart the system and then change everything to 0409) You must restart the system at this point.

How to use Redis cache in PHP array pagination? How to use Redis cache in PHP array pagination? May 01, 2024 am 10:48 AM

Using Redis cache can greatly optimize the performance of PHP array paging. This can be achieved through the following steps: Install the Redis client. Connect to the Redis server. Create cache data and store each page of data into a Redis hash with the key "page:{page_number}". Get data from cache and avoid expensive operations on large arrays.

How to find the update file downloaded by Win11_Share the location of the update file downloaded by Win11 How to find the update file downloaded by Win11_Share the location of the update file downloaded by Win11 May 08, 2024 am 10:34 AM

1. First, double-click the [This PC] icon on the desktop to open it. 2. Then double-click the left mouse button to enter [C drive]. System files will generally be automatically stored in C drive. 3. Then find the [windows] folder in the C drive and double-click to enter. 4. After entering the [windows] folder, find the [SoftwareDistribution] folder. 5. After entering, find the [download] folder, which contains all win11 download and update files. 6. If we want to delete these files, just delete them directly in this folder.

PHP Redis caching applications and best practices PHP Redis caching applications and best practices May 04, 2024 am 08:33 AM

Redis is a high-performance key-value cache. The PHPRedis extension provides an API to interact with the Redis server. Use the following steps to connect to Redis, store and retrieve data: Connect: Use the Redis classes to connect to the server. Storage: Use the set method to set key-value pairs. Retrieval: Use the get method to obtain the value of the key.

Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Apr 01, 2025 pm 03:06 PM

Causes and solutions for errors when using PECL to install extensions in Docker environment When using Docker environment, we often encounter some headaches...

See all articles