PHP database redis usage and analysis

墨辰丷
Release: 2023-03-26 15:48:01
Original
1209 people have browsed it

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]//关闭服务器[不存储]
Copy after login

list(linked list) command

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

set(set) command

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

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
Copy after login

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
Copy after login


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          //导出的文件路径
Copy after login

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时重写
Copy after login

redis的主从复制

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

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

port 6380
pidfile filename
slave-read-only yes
masterauth password
Copy after login

设置完成后,分别用不同的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秒内哨兵不再试图恢复原主服务器
Copy after login

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);       //获取值
Copy after login

相关推荐:

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template