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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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.

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)

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

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.

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.

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
