国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Database Redis Detailed introductory tutorial for Redis database

Detailed introductory tutorial for Redis database

Jun 10, 2020 pm 05:42 PM
redis

Detailed introductory tutorial for Redis database

This article mainly introduces the super powerful and detailed Redis introductory tutorial. This article introduces the knowledge of all aspects of the Redis database in detail. Friends in need can refer to it

【Directory of this tutorial】

1.What is redis
2.Who is the author of redis
3.Who is using redis
4.Learn to install redis
5. Learn to start redis
6. Use redis client
7.redis data structure – introduction
8.redis data structure – strings
9.redis data structure – lists
10.redis Data structure – collection
11.redis data structure – ordered collection
12.redis data structure – hash
13. Let’s talk about redis persistence – two ways
14. Let’s talk about redis persistence ization – RDB
15. Let’s talk about redis persistence – AOF
16. Let’s talk about redis persistence – AOF rewriting
17. Let’s talk about redis persistence – how to choose RDB and AOF
18. Let’s talk about master-slave – usage
19. Let’s talk about master-slave – synchronization principle
20. Let’s talk about redis transaction processing
21. Teach you to understand redis configuration – Introduction
22. Teach you how to read Understand redis configuration - general
23. Teach you to understand redis configuration - snapshot
24. Teach you to understand redis configuration - copy
25. Teach you to understand redis configuration - security
26. Teach Do you understand redis configuration-restrictions
27.Teach you understand redis configuration-append mode
28.Teach you understand redis configuration-LUA script
29.Teach you understand redis configuration-slow log
30. Teach you to understand redis configuration – event notification
31. Teach you to understand redis configuration – advanced configuration

[What is redis]

redis is a It is an open source Key-Value database written in C language, supports network interaction, and can be memory-based or persistent.

The official website address of redis is very easy to remember, it is redis.io. (I checked specifically and found that the domain name suffix io ??belongs to the national domain name and is the British Indian Ocean territory)

Currently, Vmware is funding the development and maintenance of the redis project.

[Who is the author of redis]

Let’s get straight to the point, let’s look at the photo first:

Is it beyond your expectation? Well, masters always have something special about them. different.

This is the author of redis, his name is Salvatore Sanfilippo, he comes from Sicily, Italy, and now lives in Catania. Currently working for Pivotal.

The online name he uses is antirez. If you are interested, you can visit his blog, the address is antirez.com, and of course you can follow his github, the address is http://github. com/antirez.

【W(wǎng)ho is using redis】

Blizzard, digg, stackoverflow, github, flickr...

【Learn to install redis】

Download from redis.io Unzip the latest version of redis-X.Y.Z.tar.gz, then enter the redis-X.Y.Z folder and make directly. The installation is very simple.

After make is successful, some binary executable files will be generated in the src folder, including redis-server, redis-cli, etc.:

Copy the code as follows:

$ find . -type f -executable
./redis-benchmark //用于進(jìn)行redis性能測(cè)試的工具
./redis-check-dump //用于修復(fù)出問(wèn)題的dump.rdb文件
./redis-cli //redis的客戶端
./redis-server //redis的服務(wù)端
./redis-check-aof //用于修復(fù)出問(wèn)題的AOF文件
./redis-sentinel //用于集群管理

【Learn to start redis】

Starting redis is very simple. You can start the server directly with ./redis-server. You can also use the following method to specify the configuration to be loaded. File:

Copy code The code is as follows:

./redis-server ../redis.conf


By default, redis-server will run in a non-daemon mode, and the default service port is 6379.

There is an interesting allusion to why the author chose 6379 as the default port. Students who are good at English can read the author’s explanation in this blog post.

[Use redis client]

Let’s look at an example directly:

Copy the code as follows:

//這樣來(lái)啟動(dòng)redis客戶端了
$ ./redis-cli
//用set指令來(lái)設(shè)置key、value
127.0.0.1:6379> set name "roc" 
OK
//來(lái)獲取name的值
127.0.0.1:6379> get name 
"roc"
//通過(guò)客戶端來(lái)關(guān)閉redis服務(wù)端
127.0.0.1:6379> shutdown 
127.0.0.1:6379>

[redis data structure – Introduction]

redis is an advanced key:value storage system, in which value supports five data types:

1. Strings (strings)
2. String lists (lists)
3. String sets (sets)
4. Ordered string sets (sorted sets)
5. Hashes

Regarding the key, there are a few points to remind everyone:

1. The key should not be too long, and try not to exceed 1024 bytes. This not only consumes memory, but also reduces the search efficiency. Efficiency; <br/>2. The key should not be too short. If it is too short, the readability of the key will be reduced; <br/>3. In a project, it is best to use a unified naming pattern for the key, such as user:10000:passwd .

[redis data structure – strings]

Some people say that if you only use the string type in redis and do not use the persistence function of redis, then redis will be the same as memcache Very, very similar. This shows that the strings type is a very basic data type and a necessary data type for any storage system.

Let’s take a look at the simplest example:

Copy the code as follows:

set mystr "hello world!" //設(shè)置字符串類型
get mystr //讀取字符串類型

The usage of string type is so simple, because it is binary safe , so you can store the contents of an image file as a string.

In addition, we can also perform numerical operations through string types:

Copy the code The code is as follows:

127.0.0.1:6379> set mynum "2"
OK
127.0.0.1:6379> get mynum
"2"
127.0.0.1:6379> incr mynum
(integer) 3
127.0.0.1:6379> get mynum
"3"

Look, when encountering numerical operations, redis Converts string type to numeric value.

由于INCR等指令本身就具有原子操作的特性,所以我們完全可以利用redis的INCR、INCRBY、DECR、DECRBY等指令來(lái)實(shí)現(xiàn)原子計(jì)數(shù)的效果,假如,在某種場(chǎng)景下有3個(gè)客戶端同時(shí)讀取了mynum的值(值為2),然后對(duì)其同時(shí)進(jìn)行了加1的操作,那么,最后mynum的值一定是5。不少網(wǎng)站都利用redis的這個(gè)特性來(lái)實(shí)現(xiàn)業(yè)務(wù)上的統(tǒng)計(jì)計(jì)數(shù)需求。

【redis數(shù)據(jù)結(jié)構(gòu) – lists】

redis的另一個(gè)重要的數(shù)據(jù)結(jié)構(gòu)叫做lists,翻譯成中文叫做“列表”。

首先要明確一點(diǎn),redis中的lists在底層實(shí)現(xiàn)上并不是數(shù)組,而是鏈表,也就是說(shuō)對(duì)于一個(gè)具有上百萬(wàn)個(gè)元素的lists來(lái)說(shuō),在頭部和尾部插入一個(gè)新元素,其時(shí)間復(fù)雜度是常數(shù)級(jí)別的,比如用LPUSH在10個(gè)元素的lists頭部插入新元素,和在上千萬(wàn)元素的lists頭部插入新元素的速度應(yīng)該是相同的。

雖然lists有這樣的優(yōu)勢(shì),但同樣有其弊端,那就是,鏈表型lists的元素定位會(huì)比較慢,而數(shù)組型lists的元素定位就會(huì)快得多。

lists的常用操作包括LPUSH、RPUSH、LRANGE等。我們可以用LPUSH在lists的左側(cè)插入一個(gè)新元素,用RPUSH在lists的右側(cè)插入一個(gè)新元素,用LRANGE命令從lists中指定一個(gè)范圍來(lái)提取元素。我們來(lái)看幾個(gè)例子:

復(fù)制代碼代碼如下:

//新建一個(gè)list叫做mylist,并在列表頭部插入元素"1"
127.0.0.1:6379> lpush mylist "1" 
//返回當(dāng)前mylist中的元素個(gè)數(shù)
(integer) 1 
//在mylist右側(cè)插入元素"2"
127.0.0.1:6379> rpush mylist "2" 
(integer) 2
//在mylist左側(cè)插入元素"0"
127.0.0.1:6379> lpush mylist "0" 
(integer) 3
//列出mylist中從編號(hào)0到編號(hào)1的元素
127.0.0.1:6379> lrange mylist 0 1 
1) "0"
2) "1"
//列出mylist中從編號(hào)0到倒數(shù)第一個(gè)元素
127.0.0.1:6379> lrange mylist 0 -1 
1) "0"
2) "1"
3) "2"

lists的應(yīng)用相當(dāng)廣泛,隨便舉幾個(gè)例子:

1.我們可以利用lists來(lái)實(shí)現(xiàn)一個(gè)消息隊(duì)列,而且可以確保先后順序,不必像mysql那樣還需要通過(guò)ORDER BY來(lái)進(jìn)行排序。
2.利用LRANGE還可以很方便的實(shí)現(xiàn)分頁(yè)的功能。
3.在博客系統(tǒng)中,每片博文的評(píng)論也可以存入一個(gè)單獨(dú)的list中。

【redis數(shù)據(jù)結(jié)構(gòu) – 集合】

redis的集合,是一種無(wú)序的集合,集合中的元素沒(méi)有先后順序。

集合相關(guān)的操作也很豐富,如添加新元素、刪除已有元素、取交集、取并集、取差集等。我們來(lái)看例子:

復(fù)制代碼代碼如下:

//向集合myset中加入一個(gè)新元素"one"
127.0.0.1:6379> sadd myset "one" 
(integer) 1
127.0.0.1:6379> sadd myset "two"
(integer) 1
//列出集合myset中的所有元素
127.0.0.1:6379> smembers myset 
1) "one"
2) "two"
//判斷元素1是否在集合myset中,返回1表示存在
127.0.0.1:6379> sismember myset "one" 
(integer) 1
//判斷元素3是否在集合myset中,返回0表示不存在
127.0.0.1:6379> sismember myset "three" 
(integer) 0
//新建一個(gè)新的集合yourset
127.0.0.1:6379> sadd yourset "1" 
(integer) 1
127.0.0.1:6379> sadd yourset "2"
(integer) 1
127.0.0.1:6379> smembers yourset
1) "1"
2) "2"
//對(duì)兩個(gè)集合求并集
127.0.0.1:6379> sunion myset yourset 
1) "1"
2) "one"
3) "2"
4) "two"

對(duì)于集合的使用,也有一些常見(jiàn)的方式,比如,QQ有一個(gè)社交功能叫做“好友標(biāo)簽”,大家可以給你的好友貼標(biāo)簽,比如“大美女”、“土豪”、“歐巴”等等,這時(shí)就可以使用redis的集合來(lái)實(shí)現(xiàn),把每一個(gè)用戶的標(biāo)簽都存儲(chǔ)在一個(gè)集合之中。

【redis數(shù)據(jù)結(jié)構(gòu) – 有序集合】

redis不但提供了無(wú)需集合(sets),還很體貼的提供了有序集合(sorted sets)。有序集合中的每個(gè)元素都關(guān)聯(lián)一個(gè)序號(hào)(score),這便是排序的依據(jù)。

很多時(shí)候,我們都將redis中的有序集合叫做zsets,這是因?yàn)樵趓edis中,有序集合相關(guān)的操作指令都是以z開(kāi)頭的,比如zrange、zadd、zrevrange、zrangebyscore等等

老規(guī)矩,我們來(lái)看幾個(gè)生動(dòng)的例子:
//新增一個(gè)有序集合myzset,并加入一個(gè)元素baidu.com,給它賦予的序號(hào)是1:

復(fù)制代碼代碼如下:

127.0.0.1:6379> zadd myzset 1 baidu.com 
(integer) 1
//向myzset中新增一個(gè)元素360.com,賦予它的序號(hào)是3
127.0.0.1:6379> zadd myzset 3 360.com 
(integer) 1
//向myzset中新增一個(gè)元素google.com,賦予它的序號(hào)是2
127.0.0.1:6379> zadd myzset 2 google.com 
(integer) 1
//列出myzset的所有元素,同時(shí)列出其序號(hào),可以看出myzset已經(jīng)是有序的了。
127.0.0.1:6379> zrange myzset 0 -1 with scores 
1) "baidu.com"
2) "1"
3) "google.com"
4) "2"
5) "360.com"
6) "3"
//只列出myzset的元素
127.0.0.1:6379> zrange myzset 0 -1 
1) "baidu.com"
2) "google.com"
3) "360.com"

【redis數(shù)據(jù)結(jié)構(gòu) – 哈希】

最后要給大家介紹的是hashes,即哈希。哈希是從redis-2.0.0版本之后才有的數(shù)據(jù)結(jié)構(gòu)。

hashes存的是字符串和字符串值之間的映射,比如一個(gè)用戶要存儲(chǔ)其全名、姓氏、年齡等等,就很適合使用哈希。

我們來(lái)看一個(gè)例子:

復(fù)制代碼代碼如下:

//建立哈希,并賦值
127.0.0.1:6379> HMSET user:001 username antirez password P1pp0 age 34 
OK
//列出哈希的內(nèi)容
127.0.0.1:6379> HGETALL user:001 
1) "username"
2) "antirez"
3) "password"
4) "P1pp0"
5) "age"
6) "34"
//更改哈希中的某一個(gè)值
127.0.0.1:6379> HSET user:001 password 12345 
(integer) 0
//再次列出哈希的內(nèi)容
127.0.0.1:6379> HGETALL user:001 
1) "username"
2) "antirez"
3) "password"
4) "12345"
5) "age"
6) "34"

有關(guān)hashes的操作,同樣很豐富,需要時(shí),大家可以從這里查詢。

【聊聊redis持久化 – 兩種方式】

redis提供了兩種持久化的方式,分別是RDB(Redis DataBase)和AOF(Append Only File)。

RDB,簡(jiǎn)而言之,就是在不同的時(shí)間點(diǎn),將redis存儲(chǔ)的數(shù)據(jù)生成快照并存儲(chǔ)到磁盤(pán)等介質(zhì)上;

AOF,則是換了一個(gè)角度來(lái)實(shí)現(xiàn)持久化,那就是將redis執(zhí)行過(guò)的所有寫(xiě)指令記錄下來(lái),在下次redis重新啟動(dòng)時(shí),只要把這些寫(xiě)指令從前到后再重復(fù)執(zhí)行一遍,就可以實(shí)現(xiàn)數(shù)據(jù)恢復(fù)了。

其實(shí)RDB和AOF兩種方式也可以同時(shí)使用,在這種情況下,如果redis重啟的話,則會(huì)優(yōu)先采用AOF方式來(lái)進(jìn)行數(shù)據(jù)恢復(fù),這是因?yàn)锳OF方式的數(shù)據(jù)恢復(fù)完整度更高。

如果你沒(méi)有數(shù)據(jù)持久化的需求,也完全可以關(guān)閉RDB和AOF方式,這樣的話,redis將變成一個(gè)純內(nèi)存數(shù)據(jù)庫(kù),就像memcache一樣。

【聊聊redis持久化 – RDB】

RDB方式,是將redis某一時(shí)刻的數(shù)據(jù)持久化到磁盤(pán)中,是一種快照式的持久化方法。

redis在進(jìn)行數(shù)據(jù)持久化的過(guò)程中,會(huì)先將數(shù)據(jù)寫(xiě)入到一個(gè)臨時(shí)文件中,待持久化過(guò)程都結(jié)束了,才會(huì)用這個(gè)臨時(shí)文件替換上次持久化好的文件。正是這種特性,讓我們可以隨時(shí)來(lái)進(jìn)行備份,因?yàn)榭煺瘴募偸峭暾捎玫摹?/p>

For RDB mode, redis will create (fork) a child process separately for persistence, and the main process will not perform any IO operations, thus ensuring the extremely high performance of redis.

If large-scale data recovery is required and the integrity of data recovery is not very sensitive, the RDB method is more efficient than the AOF method.

Although RDB has many advantages, its shortcomings cannot be ignored. If you are very sensitive to data integrity, then the RDB method is not suitable for you, because even if you persist every 5 minutes, when redis fails, there will still be nearly 5 minutes of data loss. Therefore, redis also provides another persistence method, which is AOF.

[Talk about redis persistence – AOF]

AOF, English is Append Only File, that is, only files that are not allowed to be rewritten are allowed to be appended.

As introduced before, the AOF method records the executed write instructions, and executes them again in order from front to back during data recovery. It's that simple.

We can turn on the AOF function by configuring appendonly yes in redis.conf. If there is a write operation (such as SET, etc.), redis will be appended to the end of the AOF file.

The default AOF persistence strategy is fsync once per second (fsync refers to recording the write instructions in the cache to the disk), because in this case, redis can still maintain good processing performance , even if redis fails, only the data of the last 1 second will be lost.

If when appending logs, the disk space is full, the inode is full, or the power is outage, resulting in incomplete log writing, it does not matter. Redis provides the redis-check-aof tool, which can be used Perform log repair.

Because of the append method, if no processing is done, the AOF file will become larger and larger. For this reason, redis provides an AOF file rewrite (rewrite) mechanism, that is, when the size of the AOF file When the set threshold is exceeded, redis will start the content compression of the AOF file, retaining only the minimum instruction set that can recover the data. For example, it may be more vivid. If we call the INCR instruction 100 times, 100 instructions will be stored in the AOF file, but this is obviously very inefficient. These 100 instructions can be merged into one SET instruction. This This is the principle of the rewriting mechanism.

When rewriting AOF, we still use the process of writing temporary files first and then replacing them after all is completed. Therefore, problems such as power outages and full disks will not affect the availability of AOF files. You can do this. rest assured.

Another benefit of the AOF method is explained through a "scene reproduction". When a classmate was operating redis, he accidentally executed FLUSHALL, which caused all the data in the redis memory to be cleared. This is a very tragic thing. But this is not the end of the world. As long as redis is configured with AOF persistence and the AOF file has not been rewritten, we can pause redis and edit the AOF file as quickly as possible, and delete the last line of the FLUSHALL command. , and then restart redis, you can restore all the data in redis to the state before FLUSHALL. Isn’t it amazing? This is one of the benefits of AOF persistence. But if the AOF file has been overwritten, the data cannot be recovered through this method.

Although there are many advantages, the AOF method also has shortcomings. For example, under the same data scale, AOF files are larger than RDB files. Moreover, the recovery speed of AOF method is also slower than that of RDB method.

If you execute the BGREWRITEAOF command directly, redis will generate a brand new AOF file, which includes the minimum set of commands that can restore existing data.

If you are unlucky and the AOF file is damaged, don't worry too much. Redis will not load the problematic AOF file rashly, but will exit with an error. At this time, you can repair the faulty file through the following steps:

1. Back up the damaged AOF file
2. Run redis-check-aof –fix to repair it
3. Use diff - u Take a look at the difference between the two files and confirm the problem
4. Restart redis and load the repaired AOF file

[Let’s talk about redis persistence – AOF rewriting]

We need to understand the internal working principle of AOF rewriting.

When rewriting is about to begin, redis will create (fork) a "rewriting sub-process". This sub-process will first read the existing AOF file and analyze and compress the instructions it contains. and written to a temporary file.

At the same time, the main working process will accumulate the newly received write instructions into the memory buffer and continue to write them into the original AOF file. This is to ensure that the original AOF file usability to avoid surprises during the rewrite process.

When the "Rewrite Child Process" completes the rewriting work, it will send a signal to the parent process. After receiving the signal, the parent process will append the write instructions cached in the memory to the new AOF file.

When the append is completed, redis will replace the old AOF file with the new AOF file. If there are new write instructions later, they will be appended to the new AOF file.

[Talk about redis persistence – how to choose RDB and AOF]

As for whether we should choose RDB or AOF, the official recommendation is to use both at the same time. This provides a more reliable persistence solution.

[Let’s talk about master and slave – usage]

像MySQL一樣,redis是支持主從同步的,而且也支持一主多從以及多級(jí)從結(jié)構(gòu)。

主從結(jié)構(gòu),一是為了純粹的冗余備份,二是為了提升讀性能,比如很消耗性能的SORT就可以由從服務(wù)器來(lái)承擔(dān)。

redis的主從同步是異步進(jìn)行的,這意味著主從同步不會(huì)影響主邏輯,也不會(huì)降低redis的處理性能。

主從架構(gòu)中,可以考慮關(guān)閉主服務(wù)器的數(shù)據(jù)持久化功能,只讓從服務(wù)器進(jìn)行持久化,這樣可以提高主服務(wù)器的處理性能。

在主從架構(gòu)中,從服務(wù)器通常被設(shè)置為只讀模式,這樣可以避免從服務(wù)器的數(shù)據(jù)被誤修改。但是從服務(wù)器仍然可以接受CONFIG等指令,所以還是不應(yīng)該將從服務(wù)器直接暴露到不安全的網(wǎng)絡(luò)環(huán)境中。如果必須如此,那可以考慮給重要指令進(jìn)行重命名,來(lái)避免命令被外人誤執(zhí)行。

【聊聊主從 – 同步原理】

從服務(wù)器會(huì)向主服務(wù)器發(fā)出SYNC指令,當(dāng)主服務(wù)器接到此命令后,就會(huì)調(diào)用BGSAVE指令來(lái)創(chuàng)建一個(gè)子進(jìn)程專門(mén)進(jìn)行數(shù)據(jù)持久化工作,也就是將主服務(wù)器的數(shù)據(jù)寫(xiě)入RDB文件中。在數(shù)據(jù)持久化期間,主服務(wù)器將執(zhí)行的寫(xiě)指令都緩存在內(nèi)存中。

在BGSAVE指令執(zhí)行完成后,主服務(wù)器會(huì)將持久化好的RDB文件發(fā)送給從服務(wù)器,從服務(wù)器接到此文件后會(huì)將其存儲(chǔ)到磁盤(pán)上,然后再將其讀取到內(nèi)存中。這個(gè)動(dòng)作完成后,主服務(wù)器會(huì)將這段時(shí)間緩存的寫(xiě)指令再以redis協(xié)議的格式發(fā)送給從服務(wù)器。

另外,要說(shuō)的一點(diǎn)是,即使有多個(gè)從服務(wù)器同時(shí)發(fā)來(lái)SYNC指令,主服務(wù)器也只會(huì)執(zhí)行一次BGSAVE,然后把持久化好的RDB文件發(fā)給多個(gè)下游。在redis2.8版本之前,如果從服務(wù)器與主服務(wù)器因某些原因斷開(kāi)連接的話,都會(huì)進(jìn)行一次主從之間的全量的數(shù)據(jù)同步;而在2.8版本之后,redis支持了效率更高的增量同步策略,這大大降低了連接斷開(kāi)的恢復(fù)成本。

主服務(wù)器會(huì)在內(nèi)存中維護(hù)一個(gè)緩沖區(qū),緩沖區(qū)中存儲(chǔ)著將要發(fā)給從服務(wù)器的內(nèi)容。從服務(wù)器在與主服務(wù)器出現(xiàn)網(wǎng)絡(luò)瞬斷之后,從服務(wù)器會(huì)嘗試再次與主服務(wù)器連接,一旦連接成功,從服務(wù)器就會(huì)把“希望同步的主服務(wù)器ID”和“希望請(qǐng)求的數(shù)據(jù)的偏移位置(replication offset)”發(fā)送出去。主服務(wù)器接收到這樣的同步請(qǐng)求后,首先會(huì)驗(yàn)證主服務(wù)器ID是否和自己的ID匹配,其次會(huì)檢查“請(qǐng)求的偏移位置”是否存在于自己的緩沖區(qū)中,如果兩者都滿足的話,主服務(wù)器就會(huì)向從服務(wù)器發(fā)送增量?jī)?nèi)容。

增量同步功能,需要服務(wù)器端支持全新的PSYNC指令。這個(gè)指令,只有在redis-2.8之后才具有。

【聊聊redis的事務(wù)處理】

眾所周知,事務(wù)是指“一個(gè)完整的動(dòng)作,要么全部執(zhí)行,要么什么也沒(méi)有做”。

在聊redis事務(wù)處理之前,要先和大家介紹四個(gè)redis指令,即MULTI、EXEC、DISCARD、WATCH。這四個(gè)指令構(gòu)成了redis事務(wù)處理的基礎(chǔ)。

1.MULTI用來(lái)組裝一個(gè)事務(wù);
2.EXEC用來(lái)執(zhí)行一個(gè)事務(wù);
3.DISCARD用來(lái)取消一個(gè)事務(wù);
4.WATCH用來(lái)監(jiān)視一些key,一旦這些key在事務(wù)執(zhí)行之前被改變,則取消事務(wù)的執(zhí)行。

紙上得來(lái)終覺(jué)淺,我們來(lái)看一個(gè)MULTI和EXEC的例子:

復(fù)制代碼代碼如下:

redis> MULTI //標(biāo)記事務(wù)開(kāi)始
OK
redis> INCR user_id //多條命令按順序入隊(duì)
QUEUED
redis> INCR user_id
QUEUED
redis> INCR user_id
QUEUED
redis> PING
QUEUED
redis> EXEC //執(zhí)行
1) (integer) 1
2) (integer) 2
3) (integer) 3
4) PONG

在上面的例子中,我們看到了QUEUED的字樣,這表示我們?cè)谟肕ULTI組裝事務(wù)時(shí),每一個(gè)命令都會(huì)進(jìn)入到內(nèi)存隊(duì)列中緩存起來(lái),如果出現(xiàn)QUEUED則表示我們這個(gè)命令成功插入了緩存隊(duì)列,在將來(lái)執(zhí)行EXEC時(shí),這些被QUEUED的命令都會(huì)被組裝成一個(gè)事務(wù)來(lái)執(zhí)行。

對(duì)于事務(wù)的執(zhí)行來(lái)說(shuō),如果redis開(kāi)啟了AOF持久化的話,那么一旦事務(wù)被成功執(zhí)行,事務(wù)中的命令就會(huì)通過(guò)write命令一次性寫(xiě)到磁盤(pán)中去,如果在向磁盤(pán)中寫(xiě)的過(guò)程中恰好出現(xiàn)斷電、硬件故障等問(wèn)題,那么就可能出現(xiàn)只有部分命令進(jìn)行了AOF持久化,這時(shí)AOF文件就會(huì)出現(xiàn)不完整的情況,這時(shí),我們可以使用redis-check-aof工具來(lái)修復(fù)這一問(wèn)題,這個(gè)工具會(huì)將AOF文件中不完整的信息移除,確保AOF文件完整可用。

有關(guān)事務(wù),大家經(jīng)常會(huì)遇到的是兩類錯(cuò)誤:

1.調(diào)用EXEC之前的錯(cuò)誤
2.調(diào)用EXEC之后的錯(cuò)誤

“調(diào)用EXEC之前的錯(cuò)誤”,有可能是由于語(yǔ)法有誤導(dǎo)致的,也可能時(shí)由于內(nèi)存不足導(dǎo)致的。只要出現(xiàn)某個(gè)命令無(wú)法成功寫(xiě)入緩沖隊(duì)列的情況,redis都會(huì)進(jìn)行記錄,在客戶端調(diào)用EXEC時(shí),redis會(huì)拒絕執(zhí)行這一事務(wù)。(這時(shí)2.6.5版本之后的策略。在2.6.5之前的版本中,redis會(huì)忽略那些入隊(duì)失敗的命令,只執(zhí)行那些入隊(duì)成功的命令)。我們來(lái)看一個(gè)這樣的例子:

復(fù)制代碼代碼如下:

127.0.0.1:6379> multi
OK
127.0.0.1:6379> haha //一個(gè)明顯錯(cuò)誤的指令
(error) ERR unknown command &#39;haha&#39;
127.0.0.1:6379> ping
QUEUED
127.0.0.1:6379> exec
//redis無(wú)情的拒絕了事務(wù)的執(zhí)行,原因是“之前出現(xiàn)了錯(cuò)誤”
(error) EXECABORT Transaction discarded because of previous errors.

而對(duì)于“調(diào)用EXEC之后的錯(cuò)誤”,redis則采取了完全不同的策略,即redis不會(huì)理睬這些錯(cuò)誤,而是繼續(xù)向下執(zhí)行事務(wù)中的其他命令。這是因?yàn)?,?duì)于應(yīng)用層面的錯(cuò)誤,并不是redis自身需要考慮和處理的問(wèn)題,所以一個(gè)事務(wù)中如果某一條命令執(zhí)行失敗,并不會(huì)影響接下來(lái)的其他命令的執(zhí)行。我們也來(lái)看一個(gè)例子:

復(fù)制代碼代碼如下:

127.0.0.1:6379> multi
OK
127.0.0.1:6379> set age 23
QUEUED
//age不是集合,所以如下是一條明顯錯(cuò)誤的指令
127.0.0.1:6379> sadd age 15 
QUEUED
127.0.0.1:6379> set age 29
QUEUED
127.0.0.1:6379> exec //執(zhí)行事務(wù)時(shí),redis不會(huì)理睬第2條指令執(zhí)行錯(cuò)誤
1) OK
2) (error) WRONGTYPE Operation against a key holding the wrong kind of value
3) OK
127.0.0.1:6379> get age
"29" //可以看出第3條指令被成功執(zhí)行了

好了,我們來(lái)說(shuō)說(shuō)最后一個(gè)指令“WATCH”,這是一個(gè)很好用的指令,它可以幫我們實(shí)現(xiàn)類似于“樂(lè)觀鎖”的效果,即CAS(check and set)。

WATCH本身的作用是“監(jiān)視key是否被改動(dòng)過(guò)”,而且支持同時(shí)監(jiān)視多個(gè)key,只要還沒(méi)真正觸發(fā)事務(wù),WATCH都會(huì)盡職盡責(zé)的監(jiān)視,一旦發(fā)現(xiàn)某個(gè)key被修改了,在執(zhí)行EXEC時(shí)就會(huì)返回nil,表示事務(wù)無(wú)法觸發(fā)。

復(fù)制代碼代碼如下:

127.0.0.1:6379> set age 23
OK
127.0.0.1:6379> watch age //開(kāi)始監(jiān)視age
OK
127.0.0.1:6379> set age 24 //在EXEC之前,age的值被修改了
OK
127.0.0.1:6379> multi
OK
127.0.0.1:6379> set age 25
QUEUED
127.0.0.1:6379> get age
QUEUED
127.0.0.1:6379> exec //觸發(fā)EXEC
(nil) //事務(wù)無(wú)法被執(zhí)行

【教你看懂redis配置 – 簡(jiǎn)介】

我們可以在啟動(dòng)redis-server時(shí)指定應(yīng)該加載的配置文件,方法如下:

復(fù)制代碼代碼如下:

$ ./redis-server /path/to/redis.conf

接下來(lái),我們就來(lái)講解下redis配置文件的各個(gè)配置項(xiàng)的含義,注意,本文是基于redis-2.8.4版本進(jìn)行講解的。

redis官方提供的redis.conf文件,足有700+行,其中100多行為有效配置行,另外的600多行為注釋說(shuō)明。

在配置文件的開(kāi)頭部分,首先明確了一些度量單位:

復(fù)制代碼代碼如下:

# 1k => 1000 bytes
# 1kb => 1024 bytes
# 1m => 1000000 bytes
# 1mb => 1024*1024 bytes
# 1g => 1000000000 bytes
# 1gb => 1024*1024*1024 bytes

可以看出,redis配置中對(duì)單位的大小寫(xiě)不敏感,1GB、1Gb和1gB都是相同的。由此也說(shuō)明,redis只支持bytes,不支持bit單位。

redis支持“主配置文件中引入外部配置文件”,很像C/C++中的include指令,比如:

復(fù)制代碼代碼如下:
include /path/to/other.conf

如果你看過(guò)redis的配置文件,會(huì)發(fā)現(xiàn)還是很有條理的。redis配置文件被分成了幾大塊區(qū)域,它們分別是:

1.通用(general)
2.快照(snapshotting)
3.復(fù)制(replication)
4.安全(security)
5.限制(limits)
6.追加模式(append only mode)
7.LUA腳本(lua scripting)
8.慢日志(slow log)
9.事件通知(event notification)

下面我們就來(lái)逐一講解。

【教你看懂redis配置 -通用】

默認(rèn)情況下,redis并不是以daemon形式來(lái)運(yùn)行的。通過(guò)daemonize配置項(xiàng)可以控制redis的運(yùn)行形式,如果改為yes,那么redis就會(huì)以daemon形式運(yùn)行:

復(fù)制代碼代碼如下:

daemonize no

當(dāng)以daemon形式運(yùn)行時(shí),redis會(huì)生成一個(gè)pid文件,默認(rèn)會(huì)生成在/var/run/redis.pid。當(dāng)然,你可以通過(guò)pidfile來(lái)指定pid文件生成的位置,比如:

復(fù)制代碼代碼如下:

pidfile /path/to/redis.pid

默認(rèn)情況下,redis會(huì)響應(yīng)本機(jī)所有可用網(wǎng)卡的連接請(qǐng)求。當(dāng)然,redis允許你通過(guò)bind配置項(xiàng)來(lái)指定要綁定的IP,比如:

復(fù)制代碼代碼如下:

bind 192.168.1.2 10.8.4.2


redis的默認(rèn)服務(wù)端口是6379,你可以通過(guò)port配置項(xiàng)來(lái)修改。如果端口設(shè)置為0的話,redis便不會(huì)監(jiān)聽(tīng)端口了。

復(fù)制代碼代碼如下:

port 6379


有些同學(xué)會(huì)問(wèn)“如果redis不監(jiān)聽(tīng)端口,還怎么與外界通信呢”,其實(shí)redis還支持通過(guò)unix socket方式來(lái)接收請(qǐng)求。可以通過(guò)unixsocket配置項(xiàng)來(lái)指定unix socket文件的路徑,并通過(guò)unixsocketperm來(lái)指定文件的權(quán)限。

復(fù)制代碼代碼如下:

unixsocket /tmp/redis.sock
unixsocketperm 755

當(dāng)一個(gè)redis-client一直沒(méi)有請(qǐng)求發(fā)向server端,那么server端有權(quán)主動(dòng)關(guān)閉這個(gè)連接,可以通過(guò)timeout來(lái)設(shè)置“空閑超時(shí)時(shí)限”,0表示永不關(guān)閉。

復(fù)制代碼代碼如下:

timeout 0


TCP連接?;畈呗裕梢酝ㄟ^(guò)tcp-keepalive配置項(xiàng)來(lái)進(jìn)行設(shè)置,單位為秒,假如設(shè)置為60秒,則server端會(huì)每60秒向連接空閑的客戶端發(fā)起一次ACK請(qǐng)求,以檢查客戶端是否已經(jīng)掛掉,對(duì)于無(wú)響應(yīng)的客戶端則會(huì)關(guān)閉其連接。所以關(guān)閉一個(gè)連接最長(zhǎng)需要120秒的時(shí)間。如果設(shè)置為0,則不會(huì)進(jìn)行保活檢測(cè)。

復(fù)制代碼代碼如下:

tcp-keepalive 0


redis支持通過(guò)loglevel配置項(xiàng)設(shè)置日志等級(jí),共分四級(jí),即debug、verbose、notice、warning。

復(fù)制代碼代碼如下:

loglevel notice


redis也支持通過(guò)logfile配置項(xiàng)來(lái)設(shè)置日志文件的生成位置。如果設(shè)置為空字符串,則redis會(huì)將日志輸出到標(biāo)準(zhǔn)輸出。假如你在daemon情況下將日志設(shè)置為輸出到標(biāo)準(zhǔn)輸出,則日志會(huì)被寫(xiě)到/dev/null中。

復(fù)制代碼代碼如下:

logfile ""


如果希望日志打印到syslog中,也很容易,通過(guò)syslog-enabled來(lái)控制。另外,syslog-ident還可以讓你指定syslog里的日志標(biāo)志,比如:

復(fù)制代碼代碼如下:

syslog-ident redis


而且還支持指定syslog設(shè)備,值可以是USER或LOCAL0-LOCAL7。具體可以參考syslog服務(wù)本身的用法。

復(fù)制代碼代碼如下:

syslog-facility local0


對(duì)于redis來(lái)說(shuō),可以設(shè)置其數(shù)據(jù)庫(kù)的總數(shù)量,假如你希望一個(gè)redis包含16個(gè)數(shù)據(jù)庫(kù),那么設(shè)置如下:

復(fù)制代碼代碼如下:

databases 16


這16個(gè)數(shù)據(jù)庫(kù)的編號(hào)將是0到15。默認(rèn)的數(shù)據(jù)庫(kù)是編號(hào)為0的數(shù)據(jù)庫(kù)。用戶可以使用select 來(lái)選擇相應(yīng)的數(shù)據(jù)庫(kù)。

【教你看懂redis配置 – 快照】

快照,主要涉及的是redis的RDB持久化相關(guān)的配置,我們來(lái)一起看一看。

我們可以用如下的指令來(lái)讓數(shù)據(jù)保存到磁盤(pán)上,即控制RDB快照功能:

復(fù)制代碼代碼如下:

save <seconds> <changes>


舉例來(lái)說(shuō):

復(fù)制代碼代碼如下:

save 900 1 //表示每15分鐘且至少有1個(gè)key改變,就觸發(fā)一次持久化
save 300 10 //表示每5分鐘且至少有10個(gè)key改變,就觸發(fā)一次持久化
save 60 10000 //表示每60秒至少有10000個(gè)key改變,就觸發(fā)一次持久化

如果你想禁用RDB持久化的策略,只要不設(shè)置任何save指令就可以,或者給save傳入一個(gè)空字符串參數(shù)也可以達(dá)到相同效果,就像這樣:

復(fù)制代碼代碼如下:

save ""


如果用戶開(kāi)啟了RDB快照功能,那么在redis持久化數(shù)據(jù)到磁盤(pán)時(shí)如果出現(xiàn)失敗,默認(rèn)情況下,redis會(huì)停止接受所有的寫(xiě)請(qǐng)求。這樣做的好處在于可以讓用戶很明確的知道內(nèi)存中的數(shù)據(jù)和磁盤(pán)上的數(shù)據(jù)已經(jīng)存在不一致了。如果redis不顧這種不一致,一意孤行的繼續(xù)接收寫(xiě)請(qǐng)求,就可能會(huì)引起一些災(zāi)難性的后果。

如果下一次RDB持久化成功,redis會(huì)自動(dòng)恢復(fù)接受寫(xiě)請(qǐng)求。

當(dāng)然,如果你不在乎這種數(shù)據(jù)不一致或者有其他的手段發(fā)現(xiàn)和控制這種不一致的話,你完全可以關(guān)閉這個(gè)功能,以便在快照寫(xiě)入失敗時(shí),也能確保redis繼續(xù)接受新的寫(xiě)請(qǐng)求。配置項(xiàng)如下:

復(fù)制代碼代碼如下:

stop-writes-on-bgsave-error yes

對(duì)于存儲(chǔ)到磁盤(pán)中的快照,可以設(shè)置是否進(jìn)行壓縮存儲(chǔ)。如果是的話,redis會(huì)采用LZF算法進(jìn)行壓縮。如果你不想消耗CPU來(lái)進(jìn)行壓縮的話,可以設(shè)置為關(guān)閉此功能,但是存儲(chǔ)在磁盤(pán)上的快照會(huì)比較大。

復(fù)制代碼代碼如下:

rdbcompression yes

在存儲(chǔ)快照后,我們還可以讓redis使用CRC64算法來(lái)進(jìn)行數(shù)據(jù)校驗(yàn),但是這樣做會(huì)增加大約10%的性能消耗,如果你希望獲取到最大的性能提升,可以關(guān)閉此功能。

復(fù)制代碼代碼如下:

rdbchecksum yes

我們還可以設(shè)置快照文件的名稱,默認(rèn)是這樣配置的:

復(fù)制代碼代碼如下:

dbfilename dump.rdb

最后,你還可以設(shè)置這個(gè)快照文件存放的路徑。比如默認(rèn)設(shè)置就是當(dāng)前文件夾:

復(fù)制代碼代碼如下:

dir ./

【教你看懂redis配置 – 復(fù)制】

redis提供了主從同步功能。

通過(guò)slaveof配置項(xiàng)可以控制某一個(gè)redis作為另一個(gè)redis的從服務(wù)器,通過(guò)指定IP和端口來(lái)定位到主redis的位置。一般情況下,我們會(huì)建議用戶為從redis設(shè)置一個(gè)不同頻率的快照持久化的周期,或者為從redis配置一個(gè)不同的服務(wù)端口等等。

復(fù)制代碼代碼如下:

slaveof <masterip> <masterport>


如果主redis設(shè)置了驗(yàn)證密碼的話(使用requirepass來(lái)設(shè)置),則在從redis的配置中要使用masterauth來(lái)設(shè)置校驗(yàn)密碼,否則的話,主redis會(huì)拒絕從redis的訪問(wèn)請(qǐng)求。

復(fù)制代碼代碼如下:

masterauth <master-password>

當(dāng)從redis失去了與主redis的連接,或者主從同步正在進(jìn)行中時(shí),redis該如何處理外部發(fā)來(lái)的訪問(wèn)請(qǐng)求呢?這里,從redis可以有兩種選擇:

第一種選擇:如果slave-serve-stale-data設(shè)置為yes(默認(rèn)),則從redis仍會(huì)繼續(xù)響應(yīng)客戶端的讀寫(xiě)請(qǐng)求。

第二種選擇:如果slave-serve-stale-data設(shè)置為no,則從redis會(huì)對(duì)客戶端的請(qǐng)求返回“SYNC with master in progress”,當(dāng)然也有例外,當(dāng)客戶端發(fā)來(lái)INFO請(qǐng)求和SLAVEOF請(qǐng)求,從redis還是會(huì)進(jìn)行處理。

你可以控制一個(gè)從redis是否可以接受寫(xiě)請(qǐng)求。將數(shù)據(jù)直接寫(xiě)入從redis,一般只適用于那些生命周期非常短的數(shù)據(jù),因?yàn)樵谥鲝耐綍r(shí),這些臨時(shí)數(shù)據(jù)就會(huì)被清理掉。自從redis2.6版本之后,默認(rèn)從redis為只讀。

復(fù)制代碼代碼如下:

slave-read-only yes

只讀的從redis并不適合直接暴露給不可信的客戶端。為了盡量降低風(fēng)險(xiǎn),可以使用rename-command指令來(lái)將一些可能有破壞力的命令重命名,避免外部直接調(diào)用。比如:

復(fù)制代碼代碼如下:

rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52

從redis會(huì)周期性的向主redis發(fā)出PING包。你可以通過(guò)repl_ping_slave_period指令來(lái)控制其周期。默認(rèn)是10秒。

復(fù)制代碼代碼如下:

repl-ping-slave-period 10

在主從同步時(shí),可能在這些情況下會(huì)有超時(shí)發(fā)生:

1.以從redis的角度來(lái)看,當(dāng)有大規(guī)模IO傳輸時(shí)。
2.以從redis的角度來(lái)看,當(dāng)數(shù)據(jù)傳輸或PING時(shí),主redis超時(shí)
3.以主redis的角度來(lái)看,在回復(fù)從redis的PING時(shí),從redis超時(shí)

用戶可以設(shè)置上述超時(shí)的時(shí)限,不過(guò)要確保這個(gè)時(shí)限比repl-ping-slave-period的值要大,否則每次主redis都會(huì)認(rèn)為從redis超時(shí)。

復(fù)制代碼代碼如下:

repl-timeout 60

我們可以控制在主從同步時(shí)是否禁用TCP_NODELAY。如果開(kāi)啟TCP_NODELAY,那么主redis會(huì)使用更少的TCP包和更少的帶寬來(lái)向從redis傳輸數(shù)據(jù)。但是這可能會(huì)增加一些同步的延遲,大概會(huì)達(dá)到40毫秒左右。如果你關(guān)閉了TCP_NODELAY,那么數(shù)據(jù)同步的延遲時(shí)間會(huì)降低,但是會(huì)消耗更多的帶寬。(如果你不了解TCP_NODELAY,可以到這里來(lái)科普一下)。

復(fù)制代碼代碼如下:

repl-disable-tcp-nodelay no

我們還可以設(shè)置同步隊(duì)列長(zhǎng)度。隊(duì)列長(zhǎng)度(backlog)是主redis中的一個(gè)緩沖區(qū),在與從redis斷開(kāi)連接期間,主redis會(huì)用這個(gè)緩沖區(qū)來(lái)緩存應(yīng)該發(fā)給從redis的數(shù)據(jù)。這樣的話,當(dāng)從redis重新連接上之后,就不必重新全量同步數(shù)據(jù),只需要同步這部分增量數(shù)據(jù)即可。

復(fù)制代碼代碼如下:

repl-backlog-size 1mb

如果主redis等了一段時(shí)間之后,還是無(wú)法連接到從redis,那么緩沖隊(duì)列中的數(shù)據(jù)將被清理掉。我們可以設(shè)置主redis要等待的時(shí)間長(zhǎng)度。如果設(shè)置為0,則表示永遠(yuǎn)不清理。默認(rèn)是1個(gè)小時(shí)。

復(fù)制代碼代碼如下:

repl-backlog-ttl 3600

我們可以給眾多的從redis設(shè)置優(yōu)先級(jí),在主redis持續(xù)工作不正常的情況,優(yōu)先級(jí)高的從redis將會(huì)升級(jí)為主redis。而編號(hào)越小,優(yōu)先級(jí)越高。比如一個(gè)主redis有三個(gè)從redis,優(yōu)先級(jí)編號(hào)分別為10、100、25,那么編號(hào)為10的從redis將會(huì)被首先選中升級(jí)為主redis。當(dāng)優(yōu)先級(jí)被設(shè)置為0時(shí),這個(gè)從redis將永遠(yuǎn)也不會(huì)被選中。默認(rèn)的優(yōu)先級(jí)為100。

復(fù)制代碼代碼如下:

slave-priority 100

假如主redis發(fā)現(xiàn)有超過(guò)M個(gè)從redis的連接延時(shí)大于N秒,那么主redis就停止接受外來(lái)的寫(xiě)請(qǐng)求。這是因?yàn)閺膔edis一般會(huì)每秒鐘都向主redis發(fā)出PING,而主redis會(huì)記錄每一個(gè)從redis最近一次發(fā)來(lái)PING的時(shí)間點(diǎn),所以主redis能夠了解每一個(gè)從redis的運(yùn)行情況。

復(fù)制代碼代碼如下:

min-slaves-to-write 3
min-slaves-max-lag 10

上面這個(gè)例子表示,假如有大于等于3個(gè)從redis的連接延遲大于10秒,那么主redis就不再接受外部的寫(xiě)請(qǐng)求。上述兩個(gè)配置中有一個(gè)被置為0,則這個(gè)特性將被關(guān)閉。默認(rèn)情況下min-slaves-to-write為0,而min-slaves-max-lag為10。

【教你看懂redis配置 – 安全】

我們可以要求redis客戶端在向redis-server發(fā)送請(qǐng)求之前,先進(jìn)行密碼驗(yàn)證。當(dāng)你的redis-server處于一個(gè)不太可信的網(wǎng)絡(luò)環(huán)境中時(shí),相信你會(huì)用上這個(gè)功能。由于redis性能非常高,所以每秒鐘可以完成多達(dá)15萬(wàn)次的密碼嘗試,所以你最好設(shè)置一個(gè)足夠復(fù)雜的密碼,否則很容易被黑客破解。

復(fù)制代碼代碼如下:

requirepass zhimakaimen

這里我們通過(guò)requirepass將密碼設(shè)置成“芝麻開(kāi)門(mén)”。

redis允許我們對(duì)redis指令進(jìn)行更名,比如將一些比較危險(xiǎn)的命令改個(gè)名字,避免被誤執(zhí)行。比如可以把CONFIG命令改成一個(gè)很復(fù)雜的名字,這樣可以避免外部的調(diào)用,同時(shí)還可以滿足內(nèi)部調(diào)用的需要:

復(fù)制代碼代碼如下:

rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c89

我們甚至可以禁用掉CONFIG命令,那就是把CONFIG的名字改成一個(gè)空字符串:

復(fù)制代碼代碼如下:

rename-command CONFIG ""

但需要注意的是,如果你使用AOF方式進(jìn)行數(shù)據(jù)持久化,或者需要與從redis進(jìn)行通信,那么更改指令的名字可能會(huì)引起一些問(wèn)題。

【教你看懂redis配置 -限制】

我們可以設(shè)置redis同時(shí)可以與多少個(gè)客戶端進(jìn)行連接。默認(rèn)情況下為10000個(gè)客戶端。當(dāng)你無(wú)法設(shè)置進(jìn)程文件句柄限制時(shí),redis會(huì)設(shè)置為當(dāng)前的文件句柄限制值減去32,因?yàn)閞edis會(huì)為自身內(nèi)部處理邏輯留一些句柄出來(lái)。

如果達(dá)到了此限制,redis則會(huì)拒絕新的連接請(qǐng)求,并且向這些連接請(qǐng)求方發(fā)出“max number of clients reached”以作回應(yīng)。

復(fù)制代碼代碼如下:

maxclients 10000

我們甚至可以設(shè)置redis可以使用的內(nèi)存量。一旦到達(dá)內(nèi)存使用上限,redis將會(huì)試圖移除內(nèi)部數(shù)據(jù),移除規(guī)則可以通過(guò)maxmemory-policy來(lái)指定。

如果redis無(wú)法根據(jù)移除規(guī)則來(lái)移除內(nèi)存中的數(shù)據(jù),或者我們?cè)O(shè)置了“不允許移除”,那么redis則會(huì)針對(duì)那些需要申請(qǐng)內(nèi)存的指令返回錯(cuò)誤信息,比如SET、LPUSH等。但是對(duì)于無(wú)內(nèi)存申請(qǐng)的指令,仍然會(huì)正常響應(yīng),比如GET等。

復(fù)制代碼代碼如下:

maxmemory <bytes>

需要注意的一點(diǎn)是,如果你的redis是主redis(說(shuō)明你的redis有從redis),那么在設(shè)置內(nèi)存使用上限時(shí),需要在系統(tǒng)中留出一些內(nèi)存空間給同步隊(duì)列緩存,只有在你設(shè)置的是“不移除”的情況下,才不用考慮這個(gè)因素。

對(duì)于內(nèi)存移除規(guī)則來(lái)說(shuō),redis提供了多達(dá)6種的移除規(guī)則。他們是:

1.volatile-lru:使用LRU算法移除過(guò)期集合中的key
2.allkeys-lru:使用LRU算法移除key
3.volatile-random:在過(guò)期集合中移除隨機(jī)的key
4.allkeys-random:移除隨機(jī)的key
5.volatile-ttl:移除那些TTL值最小的key,即那些最近才過(guò)期的key。
6.noeviction:不進(jìn)行移除。針對(duì)寫(xiě)操作,只是返回錯(cuò)誤信息。

無(wú)論使用上述哪一種移除規(guī)則,如果沒(méi)有合適的key可以移除的話,redis都會(huì)針對(duì)寫(xiě)請(qǐng)求返回錯(cuò)誤信息。

復(fù)制代碼代碼如下:

maxmemory-policy volatile-lru

LRU算法和最小TTL算法都并非是精確的算法,而是估算值。所以你可以設(shè)置樣本的大小。假如redis默認(rèn)會(huì)檢查三個(gè)key并選擇其中LRU的那個(gè),那么你可以改變這個(gè)key樣本的數(shù)量。

復(fù)制代碼代碼如下:

maxmemory-samples 3

最后,我們補(bǔ)充一個(gè)信息,那就是到目前版本(2.8.4)為止,redis支持的寫(xiě)指令包括了如下這些:

復(fù)制代碼代碼如下:

set setnx setex append
incr decr rpush lpush rpushx lpushx linsert lset rpoplpush sadd
sinter sinterstore sunion sunionstore sdiff sdiffstore zadd zincrby
zunionstore zinterstore hset hsetnx hmset hincrby incrby decrby
getset mset msetnx exec sort

【教你看懂redis配置 – 追加模式】

默認(rèn)情況下,redis會(huì)異步的將數(shù)據(jù)持久化到磁盤(pán)。這種模式在大部分應(yīng)用程序中已被驗(yàn)證是很有效的,但是在一些問(wèn)題發(fā)生時(shí),比如斷電,則這種機(jī)制可能會(huì)導(dǎo)致數(shù)分鐘的寫(xiě)請(qǐng)求丟失。

如博文上半部分中介紹的,追加文件(Append Only File)是一種更好的保持?jǐn)?shù)據(jù)一致性的方式。即使當(dāng)服務(wù)器斷電時(shí),也僅會(huì)有1秒鐘的寫(xiě)請(qǐng)求丟失,當(dāng)redis進(jìn)程出現(xiàn)問(wèn)題且操作系統(tǒng)運(yùn)行正常時(shí),甚至只會(huì)丟失一條寫(xiě)請(qǐng)求。

我們建議大家,AOF機(jī)制和RDB機(jī)制可以同時(shí)使用,不會(huì)有任何沖突。對(duì)于如何保持?jǐn)?shù)據(jù)一致性的討論,請(qǐng)參見(jiàn)本文。

復(fù)制代碼代碼如下:

appendonly no

我們還可以設(shè)置aof文件的名稱:

復(fù)制代碼代碼如下:

appendfilename "appendonly.aof"

fsync()調(diào)用,用來(lái)告訴操作系統(tǒng)立即將緩存的指令寫(xiě)入磁盤(pán)。一些操作系統(tǒng)會(huì)“立即”進(jìn)行,而另外一些操作系統(tǒng)則會(huì)“盡快”進(jìn)行。

redis支持三種不同的模式:

1.no:不調(diào)用fsync()。而是讓操作系統(tǒng)自行決定sync的時(shí)間。這種模式下,redis的性能會(huì)最快。
2.always:在每次寫(xiě)請(qǐng)求后都調(diào)用fsync()。這種模式下,redis會(huì)相對(duì)較慢,但數(shù)據(jù)最安全。
3.everysec:每秒鐘調(diào)用一次fsync()。這是性能和安全的折衷。

默認(rèn)情況下為everysec。有關(guān)數(shù)據(jù)一致性的揭秘,可以參考本文。

復(fù)制代碼代碼如下:

appendfsync everysec

當(dāng)fsync方式設(shè)置為always或everysec時(shí),如果后臺(tái)持久化進(jìn)程需要執(zhí)行一個(gè)很大的磁盤(pán)IO操作,那么redis可能會(huì)在fsync()調(diào)用時(shí)卡住。目前尚未修復(fù)這個(gè)問(wèn)題,這是因?yàn)榧词刮覀冊(cè)诹硪粋€(gè)新的線程中去執(zhí)行fsync(),也會(huì)阻塞住同步寫(xiě)調(diào)用。

為了緩解這個(gè)問(wèn)題,我們可以使用下面的配置項(xiàng),這樣的話,當(dāng)BGSAVE或BGWRITEAOF運(yùn)行時(shí),fsync()在主進(jìn)程中的調(diào)用會(huì)被阻止。這意味著當(dāng)另一路進(jìn)程正在對(duì)AOF文件進(jìn)行重構(gòu)時(shí),redis的持久化功能就失效了,就好像我們?cè)O(shè)置了“appendsync none”一樣。如果你的redis有時(shí)延問(wèn)題,那么請(qǐng)將下面的選項(xiàng)設(shè)置為yes。否則請(qǐng)保持no,因?yàn)檫@是保證數(shù)據(jù)完整性的最安全的選擇。

復(fù)制代碼代碼如下:

no-appendfsync-on-rewrite no

我們?cè)试Sredis自動(dòng)重寫(xiě)aof。當(dāng)aof增長(zhǎng)到一定規(guī)模時(shí),redis會(huì)隱式調(diào)用BGREWRITEAOF來(lái)重寫(xiě)log文件,以縮減文件體積。

redis是這樣工作的:redis會(huì)記錄上次重寫(xiě)時(shí)的aof大小。假如redis自啟動(dòng)至今還沒(méi)有進(jìn)行過(guò)重寫(xiě),那么啟動(dòng)時(shí)aof文件的大小會(huì)被作為基準(zhǔn)值。這個(gè)基準(zhǔn)值會(huì)和當(dāng)前的aof大小進(jìn)行比較。如果當(dāng)前aof大小超出所設(shè)置的增長(zhǎng)比例,則會(huì)觸發(fā)重寫(xiě)。另外,你還需要設(shè)置一個(gè)最小大小,是為了防止在aof很小時(shí)就觸發(fā)重寫(xiě)。

復(fù)制代碼代碼如下:

auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb

如果設(shè)置auto-aof-rewrite-percentage為0,則會(huì)關(guān)閉此重寫(xiě)功能。

【教你看懂redis配置 – LUA腳本】

lua腳本的最大運(yùn)行時(shí)間是需要被嚴(yán)格限制的,要注意單位是毫秒:

復(fù)制代碼代碼如下:

lua-time-limit 5000

如果此值設(shè)置為0或負(fù)數(shù),則既不會(huì)有報(bào)錯(cuò)也不會(huì)有時(shí)間限制。

【教你看懂redis配置 – 慢日志】

redis慢日志是指一個(gè)系統(tǒng)進(jìn)行日志查詢超過(guò)了指定的時(shí)長(zhǎng)。這個(gè)時(shí)長(zhǎng)不包括IO操作,比如與客戶端的交互、發(fā)送響應(yīng)內(nèi)容等,而僅包括實(shí)際執(zhí)行查詢命令的時(shí)間。

針對(duì)慢日志,你可以設(shè)置兩個(gè)參數(shù),一個(gè)是執(zhí)行時(shí)長(zhǎng),單位是微秒,另一個(gè)是慢日志的長(zhǎng)度。當(dāng)一個(gè)新的命令被寫(xiě)入日志時(shí),最老的一條會(huì)從命令日志隊(duì)列中被移除。

單位是微秒,即1000000表示一秒。負(fù)數(shù)則會(huì)禁用慢日志功能,而0則表示強(qiáng)制記錄每一個(gè)命令。

復(fù)制代碼代碼如下:

slowlog-log-slower-than 10000

慢日志最大長(zhǎng)度,可以隨便填寫(xiě)數(shù)值,沒(méi)有上限,但要注意它會(huì)消耗內(nèi)存。你可以使用SLOWLOG RESET來(lái)重設(shè)這個(gè)值。

復(fù)制代碼代碼如下:

slowlog-max-len 128

【教你看懂redis配置 – 事件通知】

redis可以向客戶端通知某些事件的發(fā)生。這個(gè)特性的具體解釋可以參見(jiàn)本文。

【教你看懂redis配置 – 高級(jí)配置】

有關(guān)哈希數(shù)據(jù)結(jié)構(gòu)的一些配置項(xiàng):

復(fù)制代碼代碼如下:

hash-max-ziplist-entries 512
hash-max-ziplist-value 64

有關(guān)列表數(shù)據(jù)結(jié)構(gòu)的一些配置項(xiàng):

復(fù)制代碼代碼如下:

list-max-ziplist-entries 512
list-max-ziplist-value 64

有關(guān)集合數(shù)據(jù)結(jié)構(gòu)的配置項(xiàng):

復(fù)制代碼代碼如下:

set-max-intset-entries 512

有關(guān)有序集合數(shù)據(jù)結(jié)構(gòu)的配置項(xiàng):

復(fù)制代碼代碼如下:

zset-max-ziplist-entries 128
zset-max-ziplist-value 64

關(guān)于是否需要再哈希的配置項(xiàng):

復(fù)制代碼代碼如下:

activerehashing yes

關(guān)于客戶端輸出緩沖的控制項(xiàng):

復(fù)制代碼代碼如下:

client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60

有關(guān)頻率的配置項(xiàng):

復(fù)制代碼代碼如下:

hz 10

有關(guān)重寫(xiě)aof的配置項(xiàng)

復(fù)制代碼代碼如下:

aof-rewrite-incremental-fsync yes

相關(guān)推薦:php教程

The above is the detailed content of Detailed introductory tutorial for Redis database. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

PHP Tutorial
1502
276
Recommended Laravel's best expansion packs: 2024 essential tools Recommended Laravel's best expansion packs: 2024 essential tools Apr 30, 2025 pm 02:18 PM

The essential Laravel extension packages for 2024 include: 1. LaravelDebugbar, used to monitor and debug code; 2. LaravelTelescope, providing detailed application monitoring; 3. LaravelHorizon, managing Redis queue tasks. These expansion packs can improve development efficiency and application performance.

Laravel environment construction and basic configuration (Windows/Mac/Linux) Laravel environment construction and basic configuration (Windows/Mac/Linux) Apr 30, 2025 pm 02:27 PM

The steps to build a Laravel environment on different operating systems are as follows: 1.Windows: Use XAMPP to install PHP and Composer, configure environment variables, and install Laravel. 2.Mac: Use Homebrew to install PHP and Composer and install Laravel. 3.Linux: Use Ubuntu to update the system, install PHP and Composer, and install Laravel. The specific commands and paths of each system are different, but the core steps are consistent to ensure the smooth construction of the Laravel development environment.

Redis: A Comparison to Traditional Database Servers Redis: A Comparison to Traditional Database Servers May 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

How to limit user resources in Linux? How to configure ulimit? How to limit user resources in Linux? How to configure ulimit? May 29, 2025 pm 11:09 PM

Linux system restricts user resources through the ulimit command to prevent excessive use of resources. 1.ulimit is a built-in shell command that can limit the number of file descriptors (-n), memory size (-v), thread count (-u), etc., which are divided into soft limit (current effective value) and hard limit (maximum upper limit). 2. Use the ulimit command directly for temporary modification, such as ulimit-n2048, but it is only valid for the current session. 3. For permanent effect, you need to modify /etc/security/limits.conf and PAM configuration files, and add sessionrequiredpam_limits.so. 4. The systemd service needs to set Lim in the unit file

Is Redis Primarily a Database? Is Redis Primarily a Database? May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Beyond SQL - The NoSQL Perspective Redis: Beyond SQL - The NoSQL Perspective May 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Steps and examples for building a dynamic PHP website with PhpStudy Steps and examples for building a dynamic PHP website with PhpStudy May 16, 2025 pm 07:54 PM

The steps to build a dynamic PHP website using PhpStudy include: 1. Install PhpStudy and start the service; 2. Configure the website root directory and database connection; 3. Write PHP scripts to generate dynamic content; 4. Debug and optimize website performance. Through these steps, you can build a fully functional dynamic PHP website from scratch.

Redis: Unveiling Its Purpose and Key Applications Redis: Unveiling Its Purpose and Key Applications May 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

See all articles