PHP database redis usage and analysis
This article mainly introduces the usage of redis in PHP database operation. It analyzes in detail the steps, methods and related precautions for installing and using redis in PHP in the form of examples. Friends in need can refer to it
The details are as follows:
Although memcache is easy to use and solves the IO problem when the database encounters high concurrency, there are still many problems to be solved:
1. Data persistence problem, memcache uses memory for storage , once the memcache server goes down, all the stored data will be lost.
2. Memcache stores a single data type and only supports key-value data. To store complex types of data, a large number of logical operations in PHP scripts are inevitably required.
Basic introduction to redis
Redis is also an in-memory non-relational database. It has all the advantages of memcache in data storage, and on the basis of memcache (for an introduction to memcache, please see the previous article :http://www.jb51.net/article/121315.htm
Added data persistence function, redis uses rdb and aof to achieve data persistence, and the server suddenly crashes It can also retain almost all the stored data.
Added string (string), set (set), sorted_set (ordered set), hash (hash), list (linked list) data types, which is much more convenient Types of storage and database operations.
Added security verification (the connection password can be set for the server).
The master-slave separation of redis and other systems are more complete (official development).
Native support for publish/subscribe and queue , caching and other tools.
Of course, compared with memcache, its database operations are also more complex.
Application scenarios and installation of redis
In addition to being used where memcache can be used, redis can also be used in:
You can use linked lists to store data and read its latest information.
You can use The sequence table stores data and reads its ranking data
You can use collections to store attention/followed information.
Download the latest version from the official website (http://redis.io/), Decompress directly, because redis has been officially compiled, directly make / make test, you can specify the installation path when making install.
After the installation is completed, mv the redis conf file in the installation package to the installation In the bin directory of the directory, it is necessary to configure and start redis.
In addition, there are the following files in the bin directory under the installation directory file.
redis-benchmark / /Performance testing tool -n xxx means issuing xxx commands to test
redis-check-aof //Tool to check aof log
redis-check-dump //Tool to check rbd log
redis- cli //Client
redis-server //Redis server process
redis-sentinel //Redis sentinel mode process
We use vim to open redis.conf to simply configure redis Server.
Change the daemonize option to yes to run in the background
database n Set up a redis server with n servers, the default is 0-15, a total of 16
port n to set up the redis server Listening port
Set requirepass yourpassword to set the password. After the client connects, use auth password to pass verification
We use the ./redis-server ./redis.conf command to open the redis server.
Use ./redis-cli [-p port] to connect to the server (default 6379).
redis commands
Basic (including string string type) commands
1 2 3 4 5 6 7 8 9 10 11 |
|
list(linked list) command
1 2 3 |
|
set(set) command
1 2 3 4 |
|
sorted_set (ordered set) command
zadd sorted_set score1 key1 score2 key2 score3 key3.. .Add key to the ordered set and define its score. The set will be sorted by score.
zrange sorted_set a b [with scores] Display the values in the ordered list from a to b. When b is -1, display all ,[Display the score of each value]
zrank/zrevrank sorted_set key Display the position of the key in the ordered set in forward/reverse order
zrem sorted_set key Delete the key in the ordered set
zcard sorted_set [m n] Calculate how many
hash (hash type) commands there are in the ordered set [with scores between m and n]
hset hashset key value Set hash The value of the table key is value
hget hashset key Get the key value of the hash table
hdel hashset key Delete a key in the hash table
hlen hashset Get the length of the hash table
Many redis commands , only a few simple ones are listed here. For specific commands, you can check the translation document on its official website or its Chinese website http://www.redis.cn/
redis transactions, publishing and subscription
Transactions in redis are similar to those in mysql, only the statements are slightly different.
1 2 3 4 5 |
|
For concurrency effects, redis has watch statement control. Once the key value monitored by the watch statement changes before the transaction is submitted, the transaction will be automatically canceled and returned. roll.
watch key1 [key2...]
unwatch Cancel all monitoring.
redis原生发布和订阅功能,它类似于设计模式中的观察者模式,被订阅对象一旦发布了新的消息,那么所有订阅对象都会收到这条消息。使用方式为:
1 2 3 4 |
|
redis的数据持久化
redis通过rdb和aof两种方式实现数据持久化,两种数据持久化方式都会占用CPU资源,拖慢redis的执行效率,一般两种模式配合使用。
rdb方式的主要原理就是达到某一写入条件后把内存中的所有数据的快照保存一份到磁盘上,数据恢复时用数据快照恢复。
aof方式是通过将每条redis执行命令记录入文本文件,恢复数据时重复执行记录的命令。
rdb方式实现数据持久化
用save/bgSave命令可以主动使用rdb方式[后台]存储rdb
修改redis.conf文件进行配置
1 2 3 4 5 6 |
|
aof方式实现数据持久化
aof持久化的问题在于将每条指令都记录下来,即使是对一个键的反复操作,这样会导致aof文件越来越大,使用aof重写将会大大减小aof文件的体积,因为它是在最后将数据库内数据的状态统一逆化为命令,而不论一个key经过了多少次变化。使用 bgrewrite 命令可手动重写aof文件。
配置redis.conf文件:
1 2 3 4 5 |
|
redis的主从复制
主从复制时,主从都要以自己的.conf文件来启动服务器。主服务器可以将rdb关闭,以从服务器来产生rdb,加快主服务器的速度。
从服务器复制一个redis6380.conf文件,设置端口,pid存放文件,只读,主服务器的密码。
1 2 3 4 |
|
设置完成后,分别用不同的conf文件打开服务器。
考虑到主服务器宕机的情况,我们用sentinel redis哨兵来监测服务器状态,在主服务器宕机之后做出反应。sentinel是redis集成的,我们只需要将安装包里的sentinel.conf文件拷贝到redis/bin目录下,使用redis-sentinel进程文件来启动服务器即可。
1 2 3 4 5 6 |
|
PHP操作redis服务器
安装好php的redis扩展后(具体可参考前面的文章 Linux下php安装Redis扩展的方法 http://www.jb51.net/article/99775.htm),就可以直接使用redis的类函数库了。
如下是典型的redis应用。
1 2 3 4 5 |
|
相关推荐:
The above is the detailed content of PHP database redis usage and analysis. 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 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 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 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.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.
