search
HomeBackend DevelopmentPHP TutorialPHP database redis usage and analysis

PHP database redis usage and analysis

May 18, 2018 pm 02:21 PM
phpredisdatabase

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

set key value [ex|px n] //设置值[并设置过期时间为n秒/毫秒]
get key //获取值
del key //删除值
incby|decby key n //将key值自增或自减n
rename key newkey//覆盖原来的
select n//选择第n个数据库
ttl key //查询key的过期时间,-1表示永不过期,不存在的为-2
expire key n //设置key的过期时间为n秒 
type key //获取key的存储类型
flushdb //清除当前数据库中的值
shutdown [nosave]//关闭服务器[不存储]

list(linked list) command

lpush/rpush list value1 [value2 value3...] //将value压入链表头/尾
lpop/rpop list //弹出链表头/尾的值
llen list //获取链表长度

set(set) command

sadd set value //往集合中添加value
smembers set //查看集合中的全部数据
srem set value1[value2...]//删除集合中的元素
sismember set value //判断value是否是集合中的一个元素

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.

        redis        mysql
开始事务    multi      start transition
          事务中的query语句
执行事务    exec        commit
回滚事务    discard       roll back

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原生发布和订阅功能,它类似于设计模式中的观察者模式,被订阅对象一旦发布了新的消息,那么所有订阅对象都会收到这条消息。使用方式为:

subscribe key //订阅某个key,如果这个key发布了新的消息,则会收听到
public key value//发布消息key,值为value,返回值是收到这个消息的人的个数
unsubscribe key //取消监听
psubscribe key1 key2/pattrn //[根据模式]监听多个key


redis的数据持久化

redis通过rdb和aof两种方式实现数据持久化,两种数据持久化方式都会占用CPU资源,拖慢redis的执行效率,一般两种模式配合使用。

rdb方式的主要原理就是达到某一写入条件后把内存中的所有数据的快照保存一份到磁盘上,数据恢复时用数据快照恢复。

aof方式是通过将每条redis执行命令记录入文本文件,恢复数据时重复执行记录的命令。

rdb方式实现数据持久化

用save/bgSave命令可以主动使用rdb方式[后台]存储rdb

修改redis.conf文件进行配置

save m n          //在m秒内有n次修改即进行一次快照,保存点很重要,一般会配置多个条件,满足其中之一就保存
stop-writes-on-bgsave-error yes //在进行快照的过程中如果出错,则停止写入
rdbcompression yes     //设置进行数据压缩
rdbchecksum yes       //导入数据时检查文件是否损坏
dbfilename xxx.rdb     //导出的文件名
dir path          //导出的文件路径

aof方式实现数据持久化

aof持久化的问题在于将每条指令都记录下来,即使是对一个键的反复操作,这样会导致aof文件越来越大,使用aof重写将会大大减小aof文件的体积,因为它是在最后将数据库内数据的状态统一逆化为命令,而不论一个key经过了多少次变化。使用 bgrewrite 命令可手动重写aof文件。

配置redis.conf文件:

noapppendfsync-on-rewrite yes    //设置导出rdb时停止写入aof,aof会被写在内存队列里,dump rdb 完成后统一进行写入操作。
appendfsync everysec        //每秒写入一次
appendfilename           //path/filename.aof
auto-aof-rewrite-percentage 100   //文件大小增长100%时重写
auto-aof-rewrite-min-size 64m    //文件至少达到64m时重写

redis的主从复制

主从复制时,主从都要以自己的.conf文件来启动服务器。主服务器可以将rdb关闭,以从服务器来产生rdb,加快主服务器的速度。

从服务器复制一个redis6380.conf文件,设置端口,pid存放文件,只读,主服务器的密码。

port 6380
pidfile filename
slave-read-only yes
masterauth password

设置完成后,分别用不同的conf文件打开服务器。

考虑到主服务器宕机的情况,我们用sentinel redis哨兵来监测服务器状态,在主服务器宕机之后做出反应。sentinel是redis集成的,我们只需要将安装包里的sentinel.conf文件拷贝到redis/bin目录下,使用redis-sentinel进程文件来启动服务器即可。

port 26379                    //sentinel监听的端口号
daemonize yes                  //后台启动进程
sentinel monitor mymaster 192.168.100.211 6379 2 //设置主进程ip和端口号,并设置两个哨兵发现主服务器长时间无法连接才判定其宕机
sentinel down-after-milliseconds mymaster 30000 //30000毫秒连接不上判定为无法连接
sentinel parallel-syncs mymaster 1        //一个主服务器打开时,同时复制的从服务器数,太大的话会造成服务器瞬间拥堵
sentinel failover-timeout mymaster 900000    //在90000秒内哨兵不再试图恢复原主服务器

PHP操作redis服务器

安装好php的redis扩展后(具体可参考前面的文章 Linux下php安装Redis扩展的方法 http://www.jb51.net/article/99775.htm),就可以直接使用redis的类函数库了。

如下是典型的redis应用。

$redis=new Redis();           //实例化一个Redis对象
$redis->connect('host',port);      //连接redis服务器
$redis->auth('password');        //用密码认证
$redis->set($key,$value[,$expire_time]);//设置一个值
$content=$redis->get($key);       //获取值

相关推荐:

laravel使用Redis实现网站缓存读取实现步骤详解

CodeIgniter使用redis步骤详解

PHP操作Redis步骤详解

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!

Statement
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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

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.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

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.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools