Table of Contents
Configuration
redis use
string(string)# in /thinkphp/library/think/Cache.php
Home Database Redis How to use redis in ThinkPHP5

How to use redis in ThinkPHP5

Jun 02, 2023 pm 06:25 PM
thinkphp redis

    Premise: Because this article mainly focuses on using redis in thinkPHP5, there is no special explanation about the installation of redis, but here is a little reminder, after installing redis Be sure to enable the php.ini extension later, otherwise you will still be unable to use redis.

    Configuration

    1. Students who can use ThinkPHP5 all know that TinkPHP5 encapsulates the cache class. We only need to fill in the cache configuration items in the cache in /application/congfig.php It's ready to use (shown below).

    How to use redis in ThinkPHP5

    2. From the /thinkphp/library/think/cache/driver/Redis.php file we can see that the redis cache encapsulated here can only use the string basic type of redis. If you want This will not work if you use composite data types such as hashes or queues.

    Looking at the cache class/thinkphp/library/think/cache/Driver.php, you will find that the handler method will return a handle, so we can use all data types of redis as long as we obtain this handle where we use redis. , so you can add the gethandle method getHandler

    	/**
         * 返回句柄对象,可执行其它高级方法
         *
         * @access public
         * @return object
         */
        public function handler()
        {
            return $this->handler;
        }
    Copy after login
    	/*
        *  获取句柄
        * @param  
        */
        public static function getHandler()
        {
            return self::init();
        }
    Copy after login

    How to use redis in ThinkPHP5

    redis use

    string(string)# in /thinkphp/library/think/Cache.php

    ##Basic type, one key corresponds to one value.

    A string type value can store up to 512MB

    Illustration:

    How to use redis in ThinkPHP5

    // 创建数据
    $redis->set('key', 'value');// 获取数据
    $value = $redis->get('key');
    echo $value . PHP_EOL;// 修改数据,与创建数据一致,即覆盖数据
    $redis->set('key', 'value2');
    echo $redis->get('key') . PHP_EOL;// 追加数据
    $redis->append('key', '_value2');
    echo $redis->get('key') . PHP_EOL;// 删除数据
    $redis->del('key');
    // $redis->delete('key');
    var_dump($redis->get('key'));// 创建数据,带有效期
    $redis->set('timeout_key', 'timeout_value', 5);
    $redis->setex('timeout_key', 5, 'timeout_value');
    // 获取数据的有效期
    echo $redis->ttl('timeout_key') . PHP_EOL;// 判断是否已经写入,未写入则写入
    $redis->set('unique_key', 'unique_value');
    if (!$redis->setnx('unique_key', 'unique_value')) {
    	echo $redis->get('unique_key') . PHP_EOL;
    }// 批量创建
    $multi = ['key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'];
    $redis->mset($multi);// 批量获取
    $result = $redis->mget(array_keys($multi));
    var_dump($result);
    Copy after login

    Hash(Hash)

    Hash is a collection of key-value (key=>value) pairs; it is a mapping table of string type fields and values. Hash is particularly suitable for storing objects.

    Each hash can store 2^32 -1 key-value pairs (more than 4 billion)

    Illustration:

    How to use redis in ThinkPHP5

    // 创建 hash 表
    // 向名字叫 'hash' 的 hash表 中添加元素 ['key1' => 'val1']
    $redis->hSet('hash', 'key1', 'val1');// 获取 hash表 中键名是 key1 的值
    echo $redis->hGet('hash', 'key1') . PHP_EOL;// 获取 hash表的元素个数
    echo $redis->hLen('hash') . PHP_EOL;// 获取 hash表 中所有的键
    $keys = $redis->hKeys('hash');
    var_dump($keys);// 获取 hash表 中所有的值
    $vals = $redis->hVals('hash');
    var_dump($vals);// 获取 hash表 中所有的键值对
    // 不推荐使用这种方法获取全部数据,会导致服务器执行超时,推荐方法后边会详细介绍
    // $all = $redis->hGetAll('hash');
    // var_dump($all);// 判断 hash 表中是否存在键名是 key2 的元素
    $bool = $redis->hExists('hash', 'key2');
    echo $bool ? '存在' : '不存在' . PHP_EOL;// 批量添加元素
    $redis->hMset('hash', ['key2' => 'val2', 'key3' => 'val3']);// 批量获取元素
    $hashes = $redis->hMGet('hash', ['key1', 'key2', 'key3']);
    var_dump($hashes);// 删除 hash表
    $redis->del('hash');
    Copy after login

    List( List)

    A list is a simple list of strings, sorted in insertion order. You can add an element to the head (left) or tail (right) of the list. List types are commonly used in messaging queue services to facilitate message exchange between multiple programs. Each list can store up to about 4 billion elements, or 2^32-1 elements.

    Illustration:

    How to use redis in ThinkPHP5

    // 向队列左侧加入元素
    $redis->lPush('lists', 'X');
    $redis->lPush('lists', 'X');
    // 向队列右侧加入元素
    $redis->rPush('lists', 'Z');// 将索引为1的数据修改为 Y
    $redis->lSet('lists', 1, 'Y');// 获取 list 长度
    $length = $redis->lLen('lists');
    echo $length;// 遍历 list
    $lists = $redis->lRange('lists', 0, $length - 1);
    dump($lists);// 从左侧出队一个元素(获取并删除)
    $x = $redis->lPop('lists');
    echo $x . PHP_EOL;
    // 从右侧出队一个元素(获取并删除)
    $z = $redis->rPop('lists');
    echo $z . PHP_EOL;// 获取左侧第一个元素
    $y = $redis->lIndex('lists', 0);
    echo $y . PHP_EOL;// 删除队列
    $redis->del('lists');
    Copy after login

    Set (set)

    Redis’ Set is an unordered collection of string type.

    Like lists, the efficiency is very high when performing insertion and deletion and determining whether an element exists.

    The biggest advantage of sets is that they can perform intersection, union, and difference operations.

    The maximum number of elements that a Set can contain is 4294967295 (more than 4 billion).

    Sets are implemented through hash tables, so the complexity of adding, deleting, and searching is O(1).

    Illustration:

    How to use redis in ThinkPHP5

    // 创建集合
    $redis->sAdd('sets', 'value1', 'value2');
    // 以数组形式创建集合
    $redis->sAddArray('sets2', ['value1', 'value2', 'value3']);// 取两个集合的并集
    $union = $redis->sUnion('sets', 'sets2');
    // 取两个集合的差集
    $diff = $redis->sDiff('sets', 'sets2');
    // 取两个集合的交集
    $inter = $redis->sInter('sets', 'sets2');var_dump($union, $diff, $inter);// 获取集合数量
    $card = $redis->sCard('sets');
    echo $card . PHP_EOL;// 获取集合中全部元素
    // 不推荐使用这种方法获取全部数据,会导致服务器执行超时,推荐方法后边会详细介绍
    $sets = $redis->sMembers('sets');
    var_dump($sets);// 判断元素是否是集合中的成员
    $isMember = $redis->sIsMember('sets', 'value2');
    var_dump($isMember);// 删除集合中的元素
    $redis->sRem('sets', 'value2');
    var_dump($redis->sMembers('sets'));// 随机获取一个元素
    echo $redis->sRandMember('sets');// 随机获取一个元素并从集合中删除
    echo $redis->sPop('sets');// 删除集合
    $redis->del('sets', 'sets2');
    Copy after login

    zset (ordered set)

    Redis zset is also a collection of string type elements like set, and does not Duplicate members are allowed.

    The difference is that each element is associated with a double type score.

    Redis uses scores to sort the members of the set from small to large.

    // 添加成员
    $redis->zAdd('zset', 95, '小明');
    $redis->zAdd('zset', 99, '小刚');
    $redis->zAdd('zset', 100, '小红');// 统计成员个数
    echo $redis->zCard('zset') . PHP_EOL;// 获取某个成员的分数
    $score = $redis->zScore('zset', '小明');
    echo $score . PHP_EOL;// 获取某个成员的排名
    $rank = $redis->zRank('zset', '小明'); // 从低到高排序的名次
    $revRank = $redis->zRevRank('zset', '小明'); // 从高到低排序的名次
    echo $rank . PHP_EOL;
    echo $revRank . PHP_EOL;// 给指定成员增加分数
    $redis->zIncrBy('zset', 1, '小明'); // 给小明加一分// 返回指定排名范围的成员
    $range = $redis->zRange('zset', 0, 9, true); // 返回分数从低到高排序的前10名及分数
    $revRange = $redis-> zRevRange('zset', 0, 9, true); // 返回分数从高到低排序的前10名及分数
    var_dump($range);
    var_dump($revRange);// 删除成员
    $redis->zRem('zet', '小明');// 返回指定分数范围的成员
    $rangeByScore = $redis->zRangeByScore('zet', 98, 100); // 返回指定分数范围内从低到高排序的成员
    $revRangeByScore = $redis->zRevRangeByScore('zet', 98, 100); // 返回指定分数范围内从高到低排序的成员
    var_dump($rangeByScore);
    var_dump($revRangeByScore);
    Copy after login

    The above is the detailed content of How to use redis in ThinkPHP5. 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 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)

    How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

    Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

    How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

    To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

    How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

    How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

    How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

    On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

    How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

    Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

    How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

    There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

    How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

    In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

    How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

    Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

    See all articles