Table of Contents
1. Connection
2. Data type
2-1 string string
2-2 list list
2-3 hash dictionary
2-4 set set
2-5. sorted set ordered set
3. Other common methods
3 -1 Find related keys
3-2 Expiration time
Home Backend Development PHP Tutorial PHP uses Redis examples to explain

PHP uses Redis examples to explain

Feb 27, 2018 am 11:50 AM
php redis explain


Redis is an open source log-type, Key-Value database written in ANSI C language, supports network, can be memory-based and persistent, and provides APIs in multiple languages. The data types supported by Redis are String (string), List (list), Hash (dictionary), Set (collection), Sorted Set (ordered set); Redis default port is 6379.

1. Connection

$redis = new Redis();  // 实例化$redis->connect('127.0.0.1', 6379);  // 连接$redis->auth('redis密码');   // 没密码的redis可忽略此步骤
Copy after login

2. Data type

2-1 string string

// 存储或更改$redis->set('test', 'aaa');// 获取值$redis->get('test');   // aaa
Copy after login

2-2 list list

方法中的l代表list操作
Copy after login
  1. Storage

    $redis->lpush('list', 'a');    // 从左边加入$redis->lpush('list', 'b');$redis->lpush('list', 'c');        
    
    $redis->rpush('list', 'd');    // 从右边加入$redis->lset('list', 2, 'e');// 设置或更改列表指定位置的值,成功返回1,失败返回错误信息
    Copy after login
  2. Delete

    $redis->lpop('list');      // 删除左边第一个$redis->rpop('list');      // 删除右边第一个// $redis->lrem('list名', '值', num); // 根据值删除元素,第二个参数是要删除的值(值为这个值的元素要被删除),// 第三个参数 num 表示:从哪开始删、删几个,
        //num>0 从表头往表尾删,删除num个结束;
        //num<0 从表尾往表头删,删除 |num| 个;
        //num=0 移除表中所有值为&#39;b&#39;的元素
        $redis->lrem(&#39;list&#39;, &#39;b&#39;, 2);
    Copy after login
  3. Get, return array

    $redis->lrange(&#39;list&#39;, 0, -1);  // 返回一个数组。存储在key中的列表里指定范围的元素, 
        // 第一个参数是列表名
        // 第二个参数是起始位下标,
        // 第三个是结束位下标(包含结束位元素)。
        // 负数代表倒数,-1代表倒数第一个;
        // 如果起始大于结束返回空,结束大于实际长度,返回至最后一个元素。$redis->lgetrange(&#39;list&#39;, 0, 2);// 获取列表指定区间的值,同上$redis->ltrim(&#39;list&#39;, 0, 3);   // 截取并保留列表指定区间的值,其余值删除。
        // 成功返回1,失败返回错误信息。负数代表倒数$redis->lsize(&#39;list&#39;);         // 获取列表的长度$redis->lget(&#39;list&#39;, 2)        // 获取列表指定位置的值$redis->lindex(&#39;list&#39;, 2);     // 获取列表指定位置的值
    Copy after login

2-3 hash dictionary

一个string类型的field和value的映射表,特别适合用于存储对象。每个 hash 可以存储 2的32次方 - 1 键值对(40多亿)
hash表相当于 redis存储 key => value  中的key, 表内容相当于 value
方法中h代表hash操作
Copy after login
  1. Storage

    // $redis->hset(&#39;hash表&#39;, key, value);  
        // 如果hash表不存在,创建一个该hash表,如果不存在该key则设置成功,返回true,
        // 如果存在,则替换掉原来的值,返回false,失败返回false
        // 第一个参数是字典名
        $redis->hset(&#39;hashtest&#39;, &#39;a&#39;, &#39;aaa&#39;);   // 返回true
        $redis->hset(&#39;hashtest&#39;, &#39;a&#39;, &#39;bbb&#39;);  // 返回false,a的值改为bbb
        $redis->hset(&#39;hashtest&#39;, &#39;b&#39;, &#39;bbb&#39;);  // 返回true,增加b,值为bb$redis->hmset(&#39;hashtest&#39;, [1 => 1, 2 => 2, 3 => 3]);   // 批量赋值,       $redis->hincrby(&#39;hashtest&#39;, &#39;1&#39;, 1);   // hash表中的key对应的值自增1(整数),
        // 第一个参数字典名
        // 第二个参数是key名,
        // 第三个参数是自增的幅度。如果表中不存在该key,则自动添加该key,并设置值为自增幅度$redis->hincrbyfloat(&#39;hashtest&#39;, &#39;2&#39;, 1.5);        // hash表中key自增
    Copy after login
  2. Get

    $redis->hget(&#39;hash表&#39;, key);        // 获取某个key对应的值
        $redis->hget(&#39;hashtest&#39;, &#39;a&#39;); // 获取hashtest中a的值$redis->hkeys(&#39;hashtest&#39;);     // 获取hash表中的所有的keys(键名),返回一个数组   $redis->hvals(&#39;hashtest&#39;); // 获取hash表中的所有的values(值),顺序随机,返回一个数组$redis->hgetall(&#39;hashtest&#39;);   // 获取hash表中所有的键值对,顺序随机,返回一个数组$redis->hlen(&#39;hashtest&#39;);      // 获取hash表中key的数量   $redis->hmget(&#39;hashtest&#39;, [1, 2, 3]); // 批量获取多个key对应的value,第二个参数是keyArr
    
    $redis->hexists(&#39;hashtest&#39;, &#39;b&#39;);      // 判断hash表中是否存在该key
    Copy after login
  3. Delete

    $redis->hdel(&#39;hashtest&#39;, &#39;a&#39;); 
        // 删除hash表中的一个key,成功返回true,
        // 如果表不存在或key不存在返回false
    Copy after login

2-4 set set

Redis 的 Set 是 String 类型的无序集合。集合成员是唯一的,这就意味着集合中不能出现重复的数据。
集合中最大的成员数为 2的32次方 - 1 (4294967295, 每个集合可存储40多亿个成员)。
方法中的s代表set操作
Copy after login
  1. Add

    // $redis->sadd(&#39;set集合&#39;, &#39;值&#39;); // 往settest中加入一个值,成功,返回添加的个数,失败返回0。// 第一个参数是set集合名// 第二个参数是往该集合插入新值,即:往value中插入新值
        $redis->sadd(&#39;settest&#39;, &#39;a&#39;);  // 1
        $redis->sadd(&#39;settest&#39;, &#39;b&#39;);  // 1
        $redis->sadd(&#39;settest&#39;, &#39;a&#39;);  // 0$redis->sadd(&#39;settest&#39;, [&#39;c&#39;, &#39;d&#39;, &#39;e&#39;]);  // 一次添加多个值
    Copy after login
  2. Get

    $redis->smembers(&#39;settest&#39;);   // 获取集合中所有的元素$redis->sismember(&#39;settest&#39;, &#39;b&#39;); // 判断元素是否是set成员$redis->scard(&#39;settest&#39;);      // 查看集合中元素的数量$redis->sinter(&#39;settest&#39;, &#39;settest2&#39;); // 返回两个集合的交集$redis->sinterstore(&#39;settest3&#39;, &#39;settest&#39;, &#39;settest2&#39;);    // 将settest和settest2的交集放到集合settest3中$redis->sunion(&#39;settest&#39;, &#39;settest2&#39;); // 返回两个集合的并集$redis->sunionstore(&#39;settest4&#39;, &#39;settest&#39;, &#39;settest2&#39;);    // 将settest和settest2的并集放到集合settest4中$redis->sdiff(&#39;settest&#39;, &#39;settest2&#39;);  // 返回两个集合的差集$redis->sdiffstore(&#39;settest5&#39;, &#39;settest&#39;, &#39;settest2&#39;); // 将settest和settest2的差集放到集合settest5中
    Copy after login
  3. Delete

    $redis->srem(&#39;settest&#39;, &#39;a&#39;);  // 删除集合中的某个值,$redis->srem(&#39;settest&#39;, &#39;a&#39;, &#39;b&#39;); // 删除多个值    $redis->spop(&#39;settest&#39;);       // 移除集合中一个随机的元素,并返回该元素
    Copy after login

2-5. sorted set ordered set

Redis 有序集合和集合一样也是string类型元素的集合,且不允许重复的成员。
不同的是每个元素都会关联一个double类型的分数。redis正是通过分数来为集合中的成员进行从小到大的排序。
有序集合的成员是唯一的,但分数(score)却可以重复。
集合中最大的成员数为 2的32次方 - 1 (4294967295, 每个集合可存储40多亿个成员)。
方法中的z代表有序集合操作
Copy after login
  1. Add or update

    // $redis->zadd(&#39;有序集合名&#39;, 分数, 值);   // 向有序集合ztest中一个值,分数值可以是整数值或双精度浮点数。// 执行zadd时,如果不存在,则创建一个新的有序集合;// 如果ztest存在但不是有序集类型时,返回一个错误。
        $redis->zadd(&#39;ztest&#39;, 1, &#39;a&#39;); 
        $redis->zadd(&#39;ztest&#39;, 2, &#39;a&#39;); 
            // 当某元素存在时,更新这个元素的分数,并重新插入该元素,保证元素在正确的位置。
            // 但不算新添加的$redis->zadd(&#39;ztest&#39;, 分数1, 值1, 分数2, 值2);   // 向有序集合插入多个值
        $redis->zadd(&#39;ztest&#39;, 2, &#39;b&#39;, 3, &#39;c&#39;, 4, &#39;d&#39;); 
    
    $redis->zincrby(&#39;set&#39;, 2, &#39;c&#39;);  // 指定的值 c 增加 2
    Copy after login
  2. Get

    // $redis->zrange(&#39;z集合&#39;, 起始位, 结束位, 布尔值); // 获取指定区间的有序集合。返回数组。分数从小到大。// 第一个参数: 有序集合名// 第二个参数:起始位置,// 第三个参数:结束位置(包含该位置),负数代表倒数第几个,// 第四个参数:可选参数,布尔值,是否带有分数,默认false
        $redis->zrange(&#39;ztest&#39;, 0, 1);     // [&#39;a&#39;, &#39;b&#39;]   按分数排序,但是不带分数
        $redis->zrange(&#39;ztest&#39;, 0, 1, true);// [&#39;a&#39; => 2, &#39;b&#39; => 2] 按分数排序,并且携带分数 [&#39;元素&#39; => &#39;分数&#39;]$redis->zrevrange(&#39;zset&#39;, 1, 2);   // 获取指定区间的有序集合。返回数组。分数从大到小。$redis->zscore(&#39;ztest&#39;, &#39;a&#39;);  // 获取指定元素的分数$redis->zcard(&#39;zset&#39;);         // 获取存储元素的个数$redis->zcount(&#39;zset&#39;, 2, 5);  // 分数介于 2~5 的元素的个数$redis->zrangebyscore(&#39;zset&#39;, 2, 3);   // 返回分数介于 2~3 的元素,不带分数,显示方式同zrange$redis->zrangebyscore(&#39;zset&#39;, 2, 3, [&#39;withscores&#39; => true]); // 返回分数介于2~3的元素,并带分数显示,显示方式同zrange
    Copy after login
  3. Delete

    $redis->zrem(&#39;zset&#39;, &#39;c&#39;);     // 删除指定成员$redis->zremrangebyscore(&#39;set&#39;, 2, 3);     // 移除分数介于2~3的元素,返回删除的个数
    Copy after login

3. Other common methods

// 按条件查出对应的key(键),支持字符串拼接  (返回值是一个数组,即使没查出数据也会返回空数组)     // *代表任意字符任意长度, ?任意字符一个长度$redis->keys(&#39;A&#39;);  // 找出等于 A 的那个 键$redis->keys(&#39;a*&#39;);  // 找出以 a 开头,后面为任意值的 键,$redis->keys(&#39;*b*&#39;);  // 找出链接中间包含 b 的 键$redis->keys(&#39;c??&#39;);   // 找出长度为3,且第一个字符为c的 键$a = a;$redis->keys($a . &#39;*&#39;);// 使用keys后可以使用for循环加 get() 来获取相关keys对应的值
Copy after login

3-2 Expiration time

  1. View expiration time

    // $redis->ttl(&#39;key名&#39;);        // 查看某个key有效期的剩余时间,返回秒数。  // 当 无过期时间 时,返回:-1; // 当 无该key值 时,返回-2; 
        $redis->ttl(&#39;ttltest&#39;);    // 查看ttltest剩余过期时间
    Copy after login
  2. Set expiration time

    Redis::expire(&#39;key&#39;, second);  // 多少秒后过期Redis::expireAt(&#39;key&#39;, timeStemp);  // 到某一个 时间戳(秒) 的时候过期
    Copy after login

    Related recommendations:

    How does PHP use redis message queue to publish micro

    Detailed explanation of PHP using Redis instances

    php uses Redis to implement methods to prevent secondary writing under large concurrency

    The above is the detailed content of PHP uses Redis examples to explain. 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

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
The Continued Use of PHP: Reasons for Its Endurance The Continued Use of PHP: Reasons for Its Endurance Apr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot? What should I do if the Redis cache of OAuth2Authorization object fails in Spring Boot? Apr 19, 2025 pm 08:03 PM

In SpringBoot, use Redis to cache OAuth2Authorization object. In SpringBoot application, use SpringSecurityOAuth2AuthorizationServer...

Redis's Role: Exploring the Data Storage and Management Capabilities Redis's Role: Exploring the Data Storage and Management Capabilities Apr 22, 2025 am 12:10 AM

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Why is the return value empty when using RedisTemplate for batch query? Why is the return value empty when using RedisTemplate for batch query? Apr 19, 2025 pm 10:15 PM

Why is the return value empty when using RedisTemplate for batch query? When using RedisTemplate for batch query operations, you may encounter the returned results...

Redis: Understanding Its Architecture and Purpose Redis: Understanding Its Architecture and Purpose Apr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

See all articles