This article was originally published on 2022-07-05 and migrated here from an old blog. Compiled by: Hermes
Commonly Used PHP Commands for Operating Redis
Redis is a high-performance key-value storage database. This article compiles commonly used Redis operation commands in PHP.
🔧 Connecting to Redis
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// Or with password
$redis->connect('127.0.0.1', 6379, 1.0, null, 0, null, 'password');
?>📌 String Type Operations
<?php
// Set value
$redis->set('key', 'value');
$redis->setex('key', 60, 'value'); // Set expiration time (seconds)
// Get value
$value = $redis->get('key');
// Increment/Decrement
$redis->incr('key'); // +1
$redis->incrBy('key', 10); // +10
$redis->decr('key'); // -1
$redis->decrBy('key', 10); // -10
// Delete
$redis->del('key');
?>📋 List Type Operations
<?php
// Insert from left/right
$redis->lPush('mylist', 'value1');
$redis->rPush('mylist', 'value2');
// Get list
$items = $redis->lRange('mylist', 0, -1);
// Pop elements
$redis->lPop('mylist'); // Pop from left
$redis->rPop('mylist'); // Pop from right
// Get list length
$len = $redis->lLen('mylist');
?>🔑 Hash Type Operations
<?php
// Set hash field
$redis->hSet('hashkey', 'field1', 'value1');
// Get hash field
$value = $redis->hGet('hashkey', 'field1');
// Get all fields
$all = $redis->hGetAll('hashkey');
// Delete field
$redis->hDel('hashkey', 'field1');
?>📦 Set Type Operations
<?php
// Add members
$redis->sAdd('setkey', 'member1');
$redis->sAdd('setkey', 'member2');
// Get all members
$members = $redis->sMembers('setkey');
// Check if member exists
$exists = $redis->sIsMember('setkey', 'member1');
// Remove member
$redis->sRem('setkey', 'member1');
?>📊 Sorted Set Type Operations
<?php
// Add members (with score)
$redis->zAdd('zsetkey', 100, 'member1');
$redis->zAdd('zsetkey', 200, 'member2');
// Get by score range
$items = $redis->zRangeByScore('zsetkey', 0, 150);
// Get rank
$rank = $redis->zRank('zsetkey', 'member1');
?>⏰ Expiration Time Management
<?php
// Set expiration time
$redis->expire('key', 60); // Expires after 60 seconds
// Check remaining time
$ttl = $redis->ttl('key');
// Remove expiration time
$redis->persist('key');
?>🔍 Common Commands
CodeBlock Loading...
💡 Best Practices
- Connection Pool: Use connection pools in high-concurrency scenarios
- Expiration Time: Set reasonable expiration times for temporary data
- Batch Operations: Use
pipelinefor batch operations to improve performance - Serialization: Use
serialize()/unserialize()for complex data
Compiled by: Hermes