Table of Contents
Redis basic data structure and PHP implementation
Home Backend Development PHP Tutorial PHP implements Redis basic data structure

PHP implements Redis basic data structure

Jul 04, 2018 pm 05:42 PM

This article mainly introduces the basic data structure of Redis implemented in PHP, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

Redis basic data structure and PHP implementation


  • Redis (REmote DIctionary Server) is an open source log type written in ANSI C language, complies with the BSD protocol, supports the network, can be based on memory and can be persisted. Key-Value database and provides APIs in multiple languages

  • Redis is often called a data structure server because the value (value) can be a string (String), a hash (Map) ), list (list), collection (Set), and ordered sets (sorted sets) and other types

##Redis configuration and connection

// Redis.php
return [
'host' => '127.0.0.1',
'port' => '6379'
];

// RedisTest.php
$redis = new redis();
$redisConf = include 'Redis.php';
$redis->connect($redisConf['host'], $redisConf['port']);
Copy after login

Redis key (Key)

// redis key操作
$redis->exists($key); // 判断key值是否存在
$redis->expire($key, 10); // 设置key在10秒后过期
Copy after login

Redis String (String)

// redis string 字符串
$redis->set($key, $val);
$redis->incr($key); // key值+1,除非val是整数,否则函数执行失败
$redis->decr($key); // key值-1,同上
$redis->append($key, "ue"); // 追加key值内容
$redis->strlen($key); // 返回key值的长度
// 当第一次设置key值后,key值的数据类型就不能改变了。
$redis->del($key); // 删除key值
Copy after login

Redis Hash(Hash)

  • Redis Hash is a string type Mapping table of field and value, hash is particularly suitable for

    storing objects

  • Each hash in Redis can store 2^(32)-1(more than 40 billion) key-value pairs

//redis hash 哈希
$redis->hset($key, 'field1', 'val1'); // 设置一个key-value键值对
$redis->hmset($key, array('field2'=>'val2', 'field3'=>'val3')); // 设置多个k-v键值对
$redis->hget($key, 'field2'); // 获取hash其中的一个键值
$redis->hmget($key, array('field2', 'field1')); // 获取hash的多个键值
$redis->hgetall($key); // 获取hash中所有的键值对
$redis->hlen($key); // 获取hash中键值对的个数
$redis->hkeys($key); // 获取hash中所有的键
$redis->hvals($key); // 获取hash中所有的值
Copy after login
Redis list(List)

  • Redis list is a simple string list ,

    Sort in order of insertion, you can add the head (left) or tail (right) of an element list

  • A list in Redis can store up to 2^( 32)-1 element

// redis list 列表
$index = $start = 0;
$redis->lpush($key, 'val1', 'val2'); // 在list的开头添加多个值
$redis->lpop($key); // 移除并获取list的第一个元素
$redis->rpop($key); // 移除并获取list的最后一个元素 $stop = $redis->llen($key) - 1; // 获取list的长度
$redis->lindex($key, $index); // 通过索引获取list元素
$redis->lrange($key, $start, $stop); // 获取指定范围内的元素
Copy after login
Redis set (Set)

  • Redis’ Set is of type String. sequence collection. Collection members are unique, which means that

    duplicate data cannot appear in the collection

  • Collections in Redis are implemented through hash tables, so adding and deleting , the search complexity is O(1)

  • A collection in Redis can store up to 2^(32)-1 members

// redis set 无序集合
$redis->sadd($key, 'val1', 'val2'); // 向集合中添加多个元素
$redis->scard($key); // 获取集合元素个数
$redis->spop($key); // 移除并获取集合内随机一个元素
$redis->srem($key, 'val1', 'val2'); // 移除集合的多个元素
$redis->sismember($key, 'val1'); // 判断元素是否存在于集合内
Copy after login
Redis ordered set (sorted set)

  • Redis ordered set, like a set, is also a collection of string type elements, and duplicate members are not allowed

  • The difference is that each element will

    be associated with a double type score . Redis uses scores to sort the members of the set from small to large

  • The members of the ordered set are unique, but the score can be repeated

  • Collections are implemented through hash tables, so the complexity of adding, deleting, and searching is O(1). The maximum number of members in the collection is 2^(32)-1

// redis sorted set 有序集合
// 有序集合里的元素都和一个分数score关联,就靠这个分数score对元素进行排序
$redis->zadd($key, $score1, $val1, $score2, $val2); // 向集合内添加多个元素
$redis->zcard($key); // 获取集合内元素总数
$redis->zcount($key, $minScore, $maxScore); // 获取集合内分类范围内的元素
$redis->zrem($key, $member1, $member2); // 移除集合内多个元素
Copy after login
Redis HyperLogLog

  • Redis HyperLogLog Yes An algorithm used to do cardinality statistics (

    Calculating the number of non-repeating elements in a data set). The advantage of HyperLogLog is that when the number or volume of input elements is very, very large, the space required to calculate the cardinality is always Fixed and very small

  • In Redis, each HyperLogLog key only costs 12 KB of memory to calculate the cardinality of nearly 2^(64) different elements. This is in sharp contrast to a collection where the more elements there are, the more memory is consumed when calculating the cardinality

  • Because HyperLogLog will only calculate the cardinality based on the input elements and will not store the input elements themselves. Therefore, HyperLogLog cannot return each input element like a collection.

$redis->pfAdd('key1', array('elem1', 'elem2'));// 添加指定元素到HyperLogLog中
$redis->pfAdd('key2', array('elem3', 'elem2'));// 将多个HyperLogLog合并为一个HyperLogLog
$redis->pfMerge('key3', array('key1', 'key2'));
$redis->pfCount('key3'); // 返回HyperLogLog的基数估计值: int(3)
Copy after login
The above is the entire content of this article. I hope it will be helpful to everyone's learning. Please pay attention to more related content. PHP Chinese website!


Related recommendations:

The difference between Define and Const in PHP

Interaction between PHP and Web pages

ob_start usage analysis in PHP

The above is the detailed content of PHP implements Redis basic data structure. 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 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 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 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 use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

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 implement the underlying redis How to implement the underlying redis Apr 10, 2025 pm 07:21 PM

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

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.

How to make message middleware for redis How to make message middleware for redis Apr 10, 2025 pm 07:51 PM

Redis, as a message middleware, supports production-consumption models, can persist messages and ensure reliable delivery. Using Redis as the message middleware enables low latency, reliable and scalable messaging.

See all articles