What 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.
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 = [ 'host' => '127.0.0.1', 'port' => 6379, 'password' => '这是你是之前设置的redis密码', 'select' => 0, 'timeout' => 20,//关闭时间 0:代表不关闭 'expire' => 0, 'persistent' => false, 'prefix' => '', ]; public function __construct($options = []) { if (!extension_loaded('redis')) { //判断是否有扩展(如果你的apache没reids扩展就会抛出这个异常) throw new \BadFunctionCallException('not support: redis'); } if (!empty($options)) { $this->options = array_merge($this->options, $options); } $func = $this->options['persistent'] ? 'pconnect' : 'connect'; //判断是否长连接 self::$handler = new \Redis; self::$handler->$func($this->options['host'], $this->options['port'], $this->options['timeout']); if ('' != $this->options['password']) { self::$handler->auth($this->options['password']); } if (0 != $this->options['select']) { self::$handler->select($this->options['select']); } } /** * 写入缓存 * @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) ? 'Mget' : 'get'; 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('RedisPackage', EXTEND_PATH);
Simple use of Redis
#设置 \RedisPackage::set('要设置的key','这是value'); #获取 $key = \RedisPackage::get('已设置的key'));
Redis extension
in the Controller to use RedisConnect redis
$redis = new \Redis(); //创建一个redis对象,下面可以直接使用$redis访问到redis对象 $redis->connect('127.0.0.1', 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('active_worker_list')
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('active_worker_list',$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('active_worker_list',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('active_worker_list')
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('active_worker_list'),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('active_worker_list');
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!

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'sServer-SideOperationsofferFunctionsandTriggersforexecutingcomplexoperationsontheserver.1)FunctionsallowcustomoperationsinLua,JavaScript,orRedis'sscriptinglanguage,enhancingscalabilityandmaintenance.2)Triggersenableautomaticfunctionexecutionone

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

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 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.

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.

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
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
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
