search
HomeDatabaseRedisWhat is the method for using Redis in ThinkPHP framework in Pagoda?

Redis is a commonly used non-relational database, mainly used for data caching. The data is saved in the form of key-value, and the key values ​​map to each other. Its data storage is different from MySQL. Its data is stored in memory, so data reading is relatively fast, which is very good for high concurrency.

Regarding the installation of redis, install the pagoda panel on the server or virtual machine to install redis, so that you can use redis very easily. Remember when installing redis, you must not only install the redis software, but also enter the php used in the project Install the redis extension in the version, and then open the redis software

1. First, find redis in the installation panel of the pagoda and click to install.

What is the method for using Redis in ThinkPHP framework in Pagoda?

2. After installing redis, click Settings and set a password

3. When installing the redis extension in the PHP environment

must be installed in In the PHP version used by the website, install the redis extension.

Create plug-in

Create the file RedisPackage.php in the extend folder of the ThinkPHP root directory. The content is as follows:

<?php
 
class RedisPackage
{
    protected static $handler = null;
    protected $options = [
        &#39;host&#39; => &#39;127.0.0.1&#39;,
        &#39;port&#39; => 6379,
        &#39;password&#39; => &#39;这是你是之前设置的redis密码&#39;,
        &#39;select&#39; => 0,
        &#39;timeout&#39; => 20,//关闭时间 0:代表不关闭
        &#39;expire&#39; => 0,
        &#39;persistent&#39; => false,
        &#39;prefix&#39; => &#39;&#39;,
    ];
 
    public function __construct($options = [])
    {
        if (!extension_loaded(&#39;redis&#39;)) {   //判断是否有扩展(如果你的apache没reids扩展就会抛出这个异常)
            throw new \BadFunctionCallException(&#39;not support: redis&#39;);
        }
        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        $func = $this->options[&#39;persistent&#39;] ? &#39;pconnect&#39; : &#39;connect&#39;;     //判断是否长连接
        self::$handler = new \Redis;
        self::$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;]) {
            self::$handler->auth($this->options[&#39;password&#39;]);
        }
 
        if (0 != $this->options[&#39;select&#39;]) {
            self::$handler->select($this->options[&#39;select&#39;]);
        }
    }
 
    /**
     * 写入缓存
     * @param string $key 键名
     * @param string $value 键值
     * @param int $exprie 过期时间 0:永不过期
     * @return bool
     */
    public static function set($key, $value, $exprie = 0)
    {
        if ($exprie == 0) {
            $set = self::$handler->set($key, $value);
        } else {
            $set = self::$handler->setex($key, $exprie, $value);
        }
        return $set;
    }
 
    /**
     * 读取缓存
     * @param string $key 键值
     * @return mixed
     */
    public static function get($key)
    {
        $fun = is_array($key) ? &#39;Mget&#39; : &#39;get&#39;;
        return self::$handler->{$fun}($key);
    }
 
    /**
     * 获取值长度
     * @param string $key
     * @return int
     */
    public static function lLen($key)
    {
        return self::$handler->lLen($key);
    }
 
    /**
     * 将一个或多个值插入到列表头部
     * @param $key
     * @param $value
     * @return int
     */
    public static function LPush($key, $value, $value2 = null, $valueN = null)
    {
        return self::$handler->lPush($key, $value, $value2, $valueN);
    }
 
    /**
     * 移出并获取列表的第一个元素
     * @param string $key
     * @return string
     */
    public static function lPop($key)
    {
        return self::$handler->lPop($key);
    }
 
 
}

The definition array $options in the class RedisPackage has a key The name is password, fill in the redis password set above here

Introduce the file

import(&#39;RedisPackage&#39;, EXTEND_PATH);

Simple use of Redis

#设置
\RedisPackage::set(&#39;要设置的key&#39;,&#39;这是value&#39;);
 
#获取
$key = \RedisPackage::get(&#39;已设置的key&#39;));

Redis extension

in the Controller to use Redis

Connect redis

$redis = new \Redis(); 
//创建一个redis对象,下面可以直接使用$redis访问到redis对象

$redis->connect(&#39;127.0.0.1&#39;, 6379);
//连接redis数据库,127.0.0.1表示本地(如果线上redis和php目录在同一个IP,则一样使用127.0.0.1),6379为redis端口号,若线上没有修改则默认是这个

Verify whether the connection is successful (can be written or not, only for verification)

$redis ->set( "test" , "redis 连接成功");
echo $redis ->get( "test");

exists() determines whether the key exists, the parameter is the key name

$redis->exists(&#39;active_worker_list&#39;)

set()

set() stores key values. The first parameter is the key name defined by yourself, and the second parameter is the data to be stored. Through this method, the data can be named and stored in the cache.

$result = $redis->set(&#39;active_worker_list&#39;,$r)

Many times we store array type data, but redis does not support reading and writing arrays, so we need to convert the array into json format

$result = $redis->set(&#39;active_worker_list&#39;,json_encode($r,true))

get()

get() gets the key value, the parameter is the key name, through this method you can get the value stored in the corresponding key

$result = $redis->get(&#39;active_worker_list&#39;)

Same as set, many times we need array type data, so we need Convert data in json format into an array

$result = json_decode($redis->get(&#39;active_worker_list&#39;),true);

del()

Sometimes for some reasons (it may be that the assignment is wrong when simply assigning a value...) we need to delete Key value, so we need to use del(), the parameter is the key name

$redis->del(&#39;active_worker_list&#39;);

The above is the detailed content of What is the method for using Redis in ThinkPHP framework in Pagoda?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis: Exploring Its Core Functionality and BenefitsRedis: Exploring Its Core Functionality and BenefitsApr 30, 2025 am 12:22 AM

Redis's core functions include memory storage and persistence mechanisms. 1) Memory storage provides extremely fast read and write speeds, suitable for high-performance applications. 2) Persistence ensures that data is not lost through RDB and AOF, and the choice is based on application needs.

Redis's Server-Side Operations: What It OffersRedis's Server-Side Operations: What It OffersApr 29, 2025 am 12:21 AM

Redis'sServer-SideOperationsofferFunctionsandTriggersforexecutingcomplexoperationsontheserver.1)FunctionsallowcustomoperationsinLua,JavaScript,orRedis'sscriptinglanguage,enhancingscalabilityandmaintenance.2)Triggersenableautomaticfunctionexecutionone

Redis: Database or Server? Demystifying the RoleRedis: Database or Server? Demystifying the RoleApr 28, 2025 am 12:06 AM

Redisisbothadatabaseandaserver.1)Asadatabase,itusesin-memorystorageforfastaccess,idealforreal-timeapplicationsandcaching.2)Asaserver,itsupportspub/submessagingandLuascriptingforreal-timecommunicationandserver-sideoperations.

Redis: The Advantages of a NoSQL ApproachRedis: The Advantages of a NoSQL ApproachApr 27, 2025 am 12:09 AM

Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

Redis: Understanding Its Architecture and PurposeRedis: Understanding Its Architecture and PurposeApr 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.

Redis vs. SQL Databases: Key DifferencesRedis vs. SQL Databases: Key DifferencesApr 25, 2025 am 12:02 AM

The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.

Redis: How It Acts as a Data Store and ServiceRedis: How It Acts as a Data Store and ServiceApr 24, 2025 am 12:08 AM

Redisactsasbothadatastoreandaservice.1)Asadatastore,itusesin-memorystorageforfastoperations,supportingvariousdatastructureslikekey-valuepairsandsortedsets.2)Asaservice,itprovidesfunctionalitieslikepub/submessagingandLuascriptingforcomplexoperationsan

Redis vs. Other Databases: A Comparative AnalysisRedis vs. Other Databases: A Comparative AnalysisApr 23, 2025 am 12:16 AM

Compared with other databases, Redis has the following unique advantages: 1) extremely fast speed, and read and write operations are usually at the microsecond level; 2) supports rich data structures and operations; 3) flexible usage scenarios such as caches, counters and publish subscriptions. When choosing Redis or other databases, it depends on the specific needs and scenarios. Redis performs well in high-performance and low-latency applications.

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

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function