Redis is an open source, network-enabled, memory-based and persistent logging, key-value database written in ANSI C, and provides multiple language apis.

This article mainly introduces the main application scenarios of Redis using PHP.

Simple string caching practice

$redis - > connect (127.0.0.1, 6379); $strCacheKey = 'Test_bihu'; / / SET application $arrCacheData = [' name '= >' job ', 'sex' = > 'male', 'age' = > '30']. $redis->set($strCacheKey, json_encode($arrCacheData)); $redis->expire($strCacheKey, 30); $json_data = $redis->get($strCacheKey); $data = json_decode($json_data); print_r($data->age); $arrWebSite = [' Google '=> ['google.com', 'google.com.hk'],]; $redis->hSet($strCacheKey, 'google', json_encode($arrWebSite['google'])); $json_data = $redis->hGet($strCacheKey, 'google'); $data = json_decode($json_data); print_r($data); // Output dataCopy the code

Simple platoon combat

$redis - > connect (127.0.0.1, 6379); $strQueueName = 'Test_bihu_queue'; / / into the 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 "---- Queue successfully ---- <br /><br />"; $strCount = $redis->lrange($strQueueName, 0, -1); Echo "<br />"; print_r($strCount); $redis->lpop($strQueueName); Echo "< br / > < br / > - queue success - < br / > < br / >"; $strCount = $redis->lrange($strQueueName, 0, -1); Echo "<br />"; print_r($strCount);Copy the code

Simple publish subscription combat

Run ini_set('default_socket_timeout', -1) under cli; $redis - > connect (127.0.0.1, 6379); $strChannel = 'Test_bihu_channel'; $redis->publish($strChannel, "push from {$strChannel} channel "); Echo "---- {$strChannel} ---- "; $redis->close();Copy the code
Cli run ini_set('default_socket_timeout', -1); $redis - > connect (127.0.0.1, 6379); $strChannel = 'Test_bihu_channel'; // subscribe to echo "---- subscribe to {$strChannel} channel and wait for notifications... ---- <br/><br/>"; $redis->subscribe([$strChannel], 'callBackFun'); function callBackFun($redis, $channel, $msg) { print_r([ 'redis' => $redis, 'channel' => $channel, 'msg' => $msg ]); }Copy the code

Simple counter combat

$redis - > connect (127.0.0.1, 6379); $strKey = 'Test_bihu_comments'; $redis->set($strKey, 0); $redis->INCR($strKey); //+1 $redis->INCR($strKey); //+1 $redis->INCR($strKey); //+1 $strNowCount = $redis->get($strKey); Echo "---- The current number is {$strNowCount}. - ";Copy the code

Leaderboard combat

$redis - > connect (127.0.0.1, 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 />"; print_r($dataOne); $dataTwo = $redis->ZRANGE($strKey, 0, -1, true); Echo "< br / > < br / > -- {$strKey} from small to large order - < br / > < br / >"; print_r($dataTwo);Copy the code

Simple string pessimistic lock combat

Explanation: The Pessimistic Lock, as the name implies, is Pessimistic.

Every time I go to get the data, I think someone else will change it, so I lock it every time I get the data.

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

When the concurrency is high, if there is no locking mechanism, then the moment the cache expires,

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

Public function lock($key = ", $key = ", $key = ", $key = "); $expire = 5) { $is_lock = $this->_redis->setnx($key, time()+$expire); // Can't get lock if(! $is_lock) {/ / whether the lock expired $lock_time = $this - > _redis - > get ($key); If (time() > $lock_time) {unlock($key); $is_lock = $this->_redis->setnx($key, time() + $expire); } } return $is_lock? true : false; } public function unlock($key = ""){return $this->_redis->del($key); } $key = 'Test_bihu_lock'; $is_lock = lock($key, 10); if ($is_lock) { echo 'get lock success<br>'; echo 'do sth.. <br>'; sleep(5); echo 'success<br>'; unlock($key); Echo 'Request too frequently<br>'; }Copy the code

Simple affairs optimistic lock actual combat

Explanation: Optimistic Lock, as the name suggests, is Optimistic.

Every time I went to pick up the data, I thought no one would change it, so I wouldn’t lock it.

The watch command will monitor the given key, and the whole transaction will fail if the monitored key has changed since the call to watch during exec.

Watch can also be called to monitor multiple keys multiple times. This allows optimistic locks to be added to the specified key.

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

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

Of course, the exec, discard, and unwatch commands remove all monitoring from the connection.

$strKey = 'Test_bihu_age'; $redis->set($strKey,10); $age = $redis->get($strKey); echo "---- Current Age:{$age} ---- <br/><br/>"; $redis->watch($strKey); $redis->multi(); $redis->set($strKey,30); New session / / echo "-- the Current Age: {$Age}, < br / > < br / >"; //30 $redis->set($strKey,20); $redis->exec(); $age = $redis->get($strKey); echo "---- Current Age:{$age} ---- <br/><br/>"; // if the watch key has changed since watch was called, the whole transaction will failCopy the code

Thanks ~