Home Backend Development PHP Tutorial When tp5 cache driver Predis php does not have a Redis driver module, use Predis to connect and use redis.

When tp5 cache driver Predis php does not have a Redis driver module, use Predis to connect and use redis.

Jun 02, 2018 pm 03:59 PM
php redis

This article mainly introduces the tp5 cache driver Predis PHP when there is no Redis driver module. Use Predis to connect and use redis. It has a certain reference value. Now I share it with you. Friends in need can refer to it

When there is no Redis driver module, use Predis to connect and use redis

Installation

composer require predis/predis
Copy after login

tp5 cache driver adds Predis.php

<?phpnamespace think\cache\driver;use think\cache\Driver;/**
 * Predis缓存驱动,就是php没有redis扩展的时候使用,适合单机部署、有前端代理实现高可用的场景,性能最好
 * 有需要在业务层实现读写分离、或者使用RedisCluster的需求,请使用Redisd驱动
 *
 * 要求安装Predis扩展:https://github.com/nrk/predis
 * 
 */class Predis extends Driver{
    protected $options = [        &#39;scheme&#39;     => &#39;tcp&#39;,        &#39;host&#39;       => &#39;127.0.0.1&#39;,        &#39;port&#39;       => 6379,        &#39;password&#39;   => &#39;&#39;,        &#39;select&#39;     => 0,        &#39;timeout&#39;    => 0,        &#39;expire&#39;     => 0,        &#39;persistent&#39; => false,        &#39;prefix&#39;     => &#39;&#39;,        &#39;database&#39;   => 15,
    ];    
    /**
     * 构造函数
     * @param array $options 缓存参数
     * @access public
     */
    public function __construct($options = [])
    {
        if (!empty($options)) {            
        $this->options = array_merge($this->options, $options);
        }        $func          = $this->options[&#39;persistent&#39;] ? &#39;pconnect&#39; : &#39;connect&#39;;        
        $this->handler = new \Predis\Client;        
        $this->handler->$func($this->options[&#39;host&#39;], $this->options[&#39;port&#39;], $this->options[&#39;timeout&#39;]);        
        if (&#39;&#39; != $this->options[&#39;password&#39;]) {            
        $this->handler->auth($this->options[&#39;password&#39;]);
        }        
        if (0 != $this->options[&#39;select&#39;]) {            
        $this->handler->select($this->options[&#39;select&#39;]);
        }
    }    /**
     * 判断缓存
     * @access public
     * @param string $name 缓存变量名
     * @return bool
     */
    public function has($name)
    {
        return $this->handler->get($this->getCacheKey($name)) ? true : false;
    }    /**
     * 读取缓存
     * @access public
     * @param string $name 缓存变量名
     * @param mixed  $default 默认值
     * @return mixed
     */
    public function get($name, $default = false)
    {
        $value = $this->handler->get($this->getCacheKey($name));        
        if (is_null($value)) {            
        return $default;
        }        
        $jsonData = json_decode($value, true);        // 检测是否为JSON数据 true 返回JSON解析数组, false返回源数据 byron sampson<xiaobo.sun@qq.com>
        return (null === $jsonData) ? $value : $jsonData;
    }    /**
     * 写入缓存
     * @access public
     * @param string    $name 缓存变量名
     * @param mixed     $value  存储数据
     * @param integer   $expire  有效时间(秒)
     * @return boolean
     */
    public function set($name, $value, $expire = null)
    {
        if (is_null($expire)) {            
        $expire = $this->options[&#39;expire&#39;];
        }        
        if ($this->tag && !$this->has($name)) {            
        $first = true;
        }        
        $key = $this->getCacheKey($name);        //对数组/对象数据进行缓存处理,保证数据完整性  byron sampson<xiaobo.sun@qq.com>
        $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;        
        if (is_int($expire) && $expire) {            
        $result = $this->handler->setex($key, $expire, $value);
        } else {            
        $result = $this->handler->set($key, $value);
        }        
        isset($first) && $this->setTagItem($key);        
        return $result;
    }    /**
     * 自增缓存(针对数值缓存)
     * @access public
     * @param string    $name 缓存变量名
     * @param int       $step 步长
     * @return false|int
     */
    public function inc($name, $step = 1)
    {
        $key = $this->getCacheKey($name);        
        return $this->handler->incrby($key, $step);
    }    /**
     * 自减缓存(针对数值缓存)
     * @access public
     * @param string    $name 缓存变量名
     * @param int       $step 步长
     * @return false|int
     */
    public function dec($name, $step = 1)
    {
        $key = $this->getCacheKey($name);        
        return $this->handler->decrby($key, $step);
    }    /**
     * 删除缓存
     * @access public
     * @param string $name 缓存变量名
     * @return boolean
     */
    public function rm($name)
    {
        return $this->handler->delete($this->getCacheKey($name));
    }    /**
     * 清除缓存
     * @access public
     * @param string $tag 标签名
     * @return boolean
     */
    public function clear($tag = null)
    {
        if ($tag) {            // 指定标签清除
            $keys = $this->getTagItem($tag);            
            foreach ($keys as $key) {                
            $this->handler->delete($key);
            }            
            $this->rm(&#39;tag_&#39; . md5($tag));            
            return true;
        }        
        return $this->handler->flushDB();
    }

}
Copy after login

Related recommendations:

PHP Method of request object in TP5 Request


The above is the detailed content of When tp5 cache driver Predis php does not have a Redis driver module, use Predis to connect and use redis.. 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

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

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

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 use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

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 read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

PHP: Is It Dying or Simply Adapting? PHP: Is It Dying or Simply Adapting? Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

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.

See all articles