PHP uses Redis in seven common scenarios

Redis is an open source, network-enabled, memory-based and persistent log, Key-Value database written in the ANSI C language, and provides multilingual API s.


This article focuses on the main scenarios for using Redis with PHP.

Simple String Cache Actual

$redis->connect('', 6379);

$strCacheKey  = 'Test_bihu';

//SET Application

$arrCacheData = [

    'name' => 'job',

    'sex'  => 'male',

    'age'  => '30'


$redis->set($strCacheKey, json_encode($arrCacheData));

$redis->expire($strCacheKey, 30);  # Expires after 30 seconds

$json_data = $redis->get($strCacheKey);

$data = json_decode($json_data);

print_r($data->age); //output data

//HSET Application

$arrWebSite = [

    'google' => [





$redis->hSet($strCacheKey, 'google', json_encode($arrWebSite['google']));

$json_data = $redis->hGet($strCacheKey, 'google');

$data = json_decode($json_data);

print_r($data); //output data


Simple Queue Actual

$redis->connect('', 6379);
$strQueueName = 'Test_bihu_queue';
$redis->rpush($strQueueName, json_encode(['uid' => 1,'name' => 'Job']));
$redis->rpush($strQueueName, json_encode(['uid' => 2,'name' => 'Tom']));
$redis->rpush($strQueueName, json_encode(['uid' => 3,'name' => 'John']));
echo "---- Successful Queue Entry ---- <br /><br />";
//View Queue
$strCount = $redis->lrange($strQueueName, 0, -1);
echo "Current queue data is: <br />";
//Out of Queue
echo "<br /><br /> ---- Queue Out Succeeded ---- <br /><br />";
//View Queue
$strCount = $redis->lrange($strQueueName, 0, -1);
echo "Current queue data is: <br />";


Simple Publish Subscription Actual

//The following is run under the content cli of the pub.php file
ini_set('default_socket_timeout', -1);
$redis->connect('', 6379);
$strChannel = 'Test_bihu_channel';
$redis->publish($strChannel, "Come from{$strChannel}Channel Push");
echo "---- {$strChannel} ---- Channel message successfully pushed~ <br/>";
//The following is run under the sub.php file content cli
ini_set('default_socket_timeout', -1);
$redis->connect('', 6379);
$strChannel = 'Test_bihu_channel';
echo "---- Subscribe{$strChannel}This channel, waiting for messages to be pushed...----  <br/><br/>";
$redis->subscribe([$strChannel], 'callBackFun');
function callBackFun($redis, $channel, $msg)
 'redis' => $redis,
 'channel' => $channel,
 'msg' => $msg


Simple Counter Actual
$redis->connect('', 6379);
$strKey = 'Test_bihu_comments';
//Set Initial Value
$redis->set($strKey, 0);
$redis->INCR($strKey);  //+1
$redis->INCR($strKey);  //+1
$redis->INCR($strKey);  //+1
$strNowCount = $redis->get($strKey);
echo "---- The current quantity is{$strNowCount}.  ---- ";


Chart Actual

$redis->connect('', 6379);
$strKey = 'Test_bihu_score';
//Store data
$redis->zadd($strKey, '50', json_encode(['name' => 'Tom']));
$redis->zadd($strKey, '70', json_encode(['name' => 'John']));
$redis->zadd($strKey, '90', json_encode(['name' => 'Jerry']));
$redis->zadd($strKey, '30', json_encode(['name' => 'Job']));
$redis->zadd($strKey, '100', json_encode(['name' => 'LiMing']));
$dataOne = $redis->ZREVRANGE($strKey, 0, -1, true);
echo "---- {$strKey}Sort from large to small ---- <br /><br />";
$dataTwo = $redis->ZRANGE($strKey, 0, -1, true);
echo "<br /><br />---- {$strKey}Sort from small to large ---- <br /><br />";


Simple String Pessimistic Lock Actual

Interpretation: Pessimistic Lock, as its name implies, is pessimistic.

Every time you go to get data, you think someone else will modify it, so every time you get data, you lock it.

Scenario: If a cache is used in the project and a timeout is set for the cache.

When concurrency is high, if there is no lock mechanism, then the cache will expire at the moment.

A large number of concurrent requests will directly query the database through the cache, causing an avalanche effect.

 * Acquire locks
 * @param  String  $key    Lock identification
 * @param  Int     $expire Lock expiration time
 * @return Boolean
public function lock($key = '', $expire = 5) {
 $is_lock = $this->_redis->setnx($key, time()+$expire);
 //Unable to acquire lock
 //Determine if the lock is out of date
 $lock_time = $this->_redis->get($key);
 //Lock expired, delete lock, reacquire
 if (time() > $lock_time) {
 $is_lock = $this->_redis->setnx($key, time() + $expire);
 return $is_lock? true : false;
 * Release lock
 * @param  String  $key Lock identification
 * @return Boolean
public function unlock($key = ''){
 return $this->_redis->del($key);
// Define Lock Identification
$key = 'Test_bihu_lock';
// Acquire locks
$is_lock = lock($key, 10);
if ($is_lock) {
 echo 'get lock success<br>';
 echo 'do sth..<br>';
 echo 'success<br>';
} else { //Failed to acquire lock
 echo 'request too frequently<br>';


Optimistic Lock for Simple Transactions

Interpretation: Optimistic Lock, as its name implies, is optimistic.

Every time you go to get the data, you assume that no one else will modify it, so you won't lock it.

The watch command monitors a given key, and when exec is exec, if the monitored key has changed since watch was called, the entire transaction will fail.

You can also call watch to monitor multiple keys multiple times.This locks the specified key optimally.

Note that the watch key is valid for the entire connection, as is the transaction.

If the connection is disconnected, monitoring and transactions are automatically cleared.

Of course, the exec, discard, unwatch commands clear all monitoring in the connection.

$strKey = 'Test_bihu_age';
$age = $redis->get($strKey);
echo "---- Current Age:{$age} ---- <br/><br/>";
// Open Transaction
//At this point a new session is opened to execute
$redis->set($strKey,30);  //new session
echo "---- Current Age:{$age} ---- <br/><br/>"; //30
$age = $redis->get($strKey);
echo "---- Current Age:{$age} ---- <br/><br/>"; //30
//When exec, if the key monitored has changed since watch was called, the entire transaction will fail 


For more information, visit:

Tencent T3-T4 standard boutique PHP architect tutorial catalogue is complete, as long as you see the guaranteed pay rise by one step (continuous update)

Keywords: PHP Redis Google Database

Added by chadbobb on Tue, 12 May 2020 09:51:38 +0300