


How to reduce the memory usage of PHP Redis (picture and text)
This article mainly introduces methods to reduce PHP Redis memory usage. Has very good reference value. Let’s take a look at it with the editor
1. Advantages of reducing redis memory usage
1. Helps reduce the time spent creating and loading snapshots
2. Improve the efficiency when loading AOF files and rewriting AOF files
3. Shorten the time required to synchronize from the server
4. No need to add additional hardware This allows redis to store more data
2. Short structure
Redis provides a set of configuration options for lists, sets, hashes, and ordered sets. , these options allow redis to store shorter structures in a more economical way.
2.1, ziplistCompressed list (list, hash, with sequel and)
Usually used storage method
When the length of the list, hash, or ordered set is short or the volume is small, redis will use a A compact storage method called ziplist is used to store these structures.
Ziplist is an unstructured representation of three different types of objects: list, hash, and ordered set. It stores data in a serialized manner. These serialized data are read every time. It needs to be decoded every time it is retrieved, and encoded every time it is written.
The difference between two-way lists and compressed lists:
In order to understand that compressed lists save more memory than other data structures, we take the list structure as an example Do in-depth research.
Typical two-way list
In a typical two-way list, each value will be represented by a node. Each node will have a pointer to the previous node and the next node in the linked list, as well as a pointer to the string value contained in the node.
The string value contained in each node will be divided into three parts for storage. Includes the string length, the number of available bytes remaining in the string value, and the null-terminated string itself.
Example:
If a certain node stores the 'abc' string, it is conservatively estimated to require 21 bytes of additional overhead (three pointers + two int+null character is: 3*4+2*4+1=21)
It can be seen from the example that storing a 3-byte string requires at least 21 bytes of additional overhead.
ziplist
A ziplist is a sequence of nodes, each containing two lengths and a string. The first length records the length of the previous node (used for traversing the compressed list from back to front); the second length is the length of the current point in the record; the stored string.
Example:
To store the string 'abc', both lengths can be stored with 1 byte, so the additional overhead is 2 bytes (the two lengths are 1 +1=2)
Conclusion:
Compressed lists reduce additional overhead by avoiding storing additional pointers and metadata. .
Configuration:
1 2 3 4 5 6 7 8 9 |
|
Test list:
1. Create the test.php file
1 2 3 4 5 6 7 8 9 |
|
The test-list at this time contains 512 pieces of data, which does not exceed the limit in the config file
2. Push to the test-list again Enter a piece of data
At this time, the test-list contains 513 pieces of data, which is larger than the 512 pieces limited in the configuration file. Indexwill abandon the ziplist storage method. Adopt its original linkedlist storage method
Hashing is the same as ordered set.
2.2, intsetIntegerSet (set)
Prerequisite, all members included in the set can be Parses as a decimal integer.
Storing collections in ordered arrays can not only reduce memory consumption, but also improve the execution speed of collection operations.
Configuration:
set-max-intset-entries 512 #Limit the number of members in the set. If it exceeds, intset will not be used. Storage
Test:
Create test.php file
1 2 3 4 5 6 7 8 9 |
|
2.3、性能问题
不管列表、散列、有序集合、集合,当超出限制的条件后,就会转换为更为典型的底层结构类型。因为随着紧凑结构的体积不断变大,操作这些结构的速度将会变得越来越慢。
测试:
#将采用list进行代表性测试
测试思路:
1、在默认配置下往test-list推入50000条数据,查看所需时间;接着在使用rpoplpush将test-list数据全部推入到新列表list-new中,查看所需时间
2、修改配置,list-max-ziplist-entries 100000,再执行上面的同样操作
3、对比时间,得出结论
默认配置下测试:
1、插入数据,查看时间
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
结果耗时4秒
2、执行相应命令,查看耗时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
更改配置文件下测试
1、先修改配置文件
list-max-ziplist-entries 100000 #将这个值修改大一点,可以更好的凸显对性能的影响
list-max-ziplist-value 64 #此值可不做修改
2、插入数据
执行test1.php
结果为:耗时12s
3、执行相应命令,查看耗时
执行test2.php
结果为:执行次数:50000,耗时12s
结论:
在本机中执行测试50000条数据就相差8s,若在高并发下,长压缩列表和大整数集合将起不到任何的优化,反而使得性能降低。
3、片结构
分片的本质就是基于简单的规则将数据划分为更小的部分,然后根据数据所属的部分来决定将数据发送到哪个位置上。很多数据库使用这种技术来扩展存储空间,并提高自己所能处理的负载量。
结合前面讲到的,我们不难发现分片结构对于redis的重要意义。因此我们需要在配置文件中关于ziplist以及intset的相关配置做出适当的调整。
3.1、分片式散列
#ShardHash.class.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
|
散列分片主要是根据基础键以及散列包含的键计算出分片键ID,然后再与基础键拼接成一个完整的分片键。在执行hset与hget以及大部分hash命令时,都需要先将key(field)通过shardKey方法处理,得到分片键才能够进行下一步操作。
3.2、分片式集合
如何构造分片式集合才能够让它更节省内存,性能更加强大呢?主要的思路就是,将集合里面的存储的数据尽量在不改变其原有功能的情况下转换成可以被解析为十进制的数据。根据前面所讲到的,当集合中的所有成员都能够被解析为十进制数据时,将会采用intset存储方式,这不仅能够节省内存,而且还可以提高响应的性能。
例子:
假若要某个大型网站需要存储每一天的唯一用户访问量。那么就可以使用将用户的唯一标识符转化成十进制数字,再存入分片式set中。
#ShardSet.class.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
4、将信息打包转换成存储字节
结合前面所讲的分片技术,采用string分片结构为大量连续的ID用户存储信息。
使用定长字符串,为每一个ID分配n个字节进行存储相应的信息。
接下来我们将采用存储用户国家、省份的例子进行讲解:
假若某个用户需要存储中国、广东省这两个信息,采用utf8字符集,那么至少需要消耗5*3=15个字节。如果网站的用户量大的话,这样的做法将会占用很多资源。接下来我们采用的方法每个用户仅仅只需要占用两个字节就可以完成存储信息。
具体思路步骤:
1、首先我们为国家、以及各国家的省份信息建立相应的'信息表格'
2、将'信息表格'建好后,也意味着每个国家,省份都有相应的索引号
3、看到这里大家应该都想到了吧,对就是使用两个索引作为用户存储的信息,不过需要注意的是我们还需要对这两个索引进行相应的处理
4、将索引当做ASCII码,将其转换为对应ASCII(0~255)所指定的字符
5、使用前面所讲的分片技术,定长分片string结构,将用户的存储位置找出来(redis中一个string不能超过512M)
6、实现信息的写入以及取出(getrange、setrange)
实现代码:
#PackBytes.class.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
|
1 2 3 |
|
1 2 3 |
|
测试:
1、dealData处理后的信息,即为'信息表表格'
2、saveCode()
userID | 国家 | 省份 |
0 | 中国 | 广东 |
13 | 日本 | 龟孙子区 |
15 | 日本 | 王八区 |
3、getMessage()
The above is the detailed content of How to reduce the memory usage of PHP Redis (picture and text). For more information, please follow other related articles on 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

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

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











PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
