Redis Common 7 Usage scenarios (PHP combat)

Source: Internet
Author: User
Redis is an open source API that is written in ANSI C, supports the web, can be persisted in memory, key-value databases, and provides multiple languages.

This article mainly introduces the use of Redis in PHP, the main application scenarios.

Simple string Cache Combat

$redis->connect (' 127.0.0.1 ', 6379); $strCacheKey  = ' Test_bihu ';//set application $arrcachedata = [    ' name ' = ' job ' ,    ' sex '  = ' male ',    ' age ' = ' + '  ]; $redis->set ($strCacheKey, Json_encode ($arrCacheData)); $ Redis->expire ($strCacheKey, +);  # set to expire after 30 seconds $json_data = $redis->get ($strCacheKey), $data = Json_decode ($json _data);p rint_r ($data->age); Output data//hset application $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);p rint_r ($data); Output data

Simple Queue Combat

$redis->connect (' 127.0.0.1 ', 6379); $strQueueName  = ' test_bihu_queue ';//Into 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 "----into the queue successfully----& Lt;br/><br/> ";//view Queue $strcount = $redis->lrange ($strQueueName, 0,-1); echo" Current queue data is: <br/> ";p rint_r ($strCount);//Out Queue $redis->lpop ($strQueueName); echo "<br/><br/>----out queue successfully----<br/><br/> ";//view Queue $strcount = $redis->lrange ($strQueueName, 0,-1); echo" Current queue data is: <br/> ";p rint_r ($strCount);

Simple release Subscription Combat

The following is the contents of the pub.php file under the CLI running Ini_set (' Default_socket_timeout ',-1); $redis->connect (' 127.0.0.1 ', 6379); $strChannel = ' Test_bihu_channel ';//Publish $redis->publish ($strChannel, "Push from {$strChannel} channel"); echo "----{$strChannel}---- Channel message Push Success ~ <br/> "; $redis->close ();
The following is the sub.php file content cli running under ini_set (' Default_socket_timeout ',-1); $redis->connect (' 127.0.0.1 ', 6379); $strChannel = ' Test_bihu_channel ';//Subscribe to echo "----subscription {$strChannel} This channel, waiting for message to be pushed ...----  <br/><br/>"; $redis Subscribe ([$strChannel], ' callbackfun '), function Callbackfun ($redis, $channel, $msg) {    print_r ([        ' Redis ' +   $redis,        ' channel ' = ' $channel,        ' msg ' +     $msg    ]);}

Simple counter Combat

$redis->connect (' 127.0.0.1 ', 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 number is {$strNowCount}. ---- ";

Leaderboard Combat

$redis->connect (' 127.0.0.1 ', 6379); $strKey = ' test_bihu_score ';//Store Data $redis->zadd ($strKey, ' ", Json_encode ( [' Name ' = ' Tom ']); $redis->zadd ($strKey, ' a ', ' Json_encode ' ([' name ' = ' John ') '), $redis->zadd ($strKey, ' n ', Json_encode ([' Name ' + ' Jerry ')); $redis->zadd ($strKey, ' a ', Json_encode ([' name ' = ' Job ')]); $redis->zadd ($strKey, ' Json_encode ([' name ' = ' liming ')); $dataOne = $redis->zrevrange ($strKey, 0,-1, true); echo "----{$strKey} Sorted by large to small----<br/><br/> ";p rint_r ($dataOne); $dataTwo = $redis->zrange ($strKey, 0,-1, true); echo" <br /><br/>----{$strKey} from small to large sort----<br/><br/> ";p rint_r ($DATATWO);

Simple string Pessimistic lock combat

Explanation: Pessimistic lock (pessimistic lock), as the name implies, is very pessimistic.

Every time I go to get the data, I think people will change it, so they lock it up every time they take the data.

Scenario: If the cache is used in the project and the cache is set to a time-out.

When the concurrency ratio is large, if there is no lock mechanism, then the cache expires instantly,

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

/** * get lock * @param String $key Lock ID * @param Int $expire Lock Expiry time * @return Boo    Lean */public function Lock ($key = ", $expire = 5) {$is _lock = $this->_redis->setnx ($key, Time () + $expire);        Cannot get lock if (! $is _lock) {//Determine if the lock expires $lock _time = $this->_redis->get ($key);            Lock expired, delete lock, retrieve if (time () > $lock _time) {unlock ($key);        $is _lock = $this->_redis->setnx ($key, Time () + $expire); }} return $is _lock? True:false;} /** * Release lock * @param String $key Lock identifier * @return Boolean */public function unlock ($key = ") {return $this->_redis-> ;d El ($key);}    Define the lock identifier $key = ' test_bihu_lock ';//get Lock $is_lock = Lock ($key, ten), if ($is _lock) {echo ' Get lock success<br> '; Echo ' do sth.    <br> ';    Sleep (5);    Echo ' success<br> '; Unlock ($key);} else {//Get lock failed echo ' request too frequently<br> ';} 

Optimistic locking of simple transactions in combat

Explanation: Optimistic Lock (optimistic lock), as the name implies, is very optimistic.

Every time I go to get the data, I think others won't change it, so they won't lock it.

The watch command monitors the given key, and the entire transaction fails if the monitored key has changed since the call to watch.

You can also call watch to monitor multiple keys more than once. This allows you to add optimistic locks to the specified key.

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

If the connection is broken, both the monitoring and the transaction are automatically purged.

Of course. The Exec,discard,unwatch command clears all monitoring in the connection.

$strKey = ' test_bihu_age '; $redis->set ($strKey); $age = $redis->get ($strKey); echo "----Current age:{$age}---- <br/><br/> "; $redis->watch ($strKey);//Open transaction $redis->multi ();//At this time a new session has been opened to execute $redis->set ($ strkey,30);  New session echo "----Current age:{$age}----<br/><br/>"; 30$redis->set ($strKey); $redis->exec (); $age = $redis->get ($strKey); echo "----Current age:{$age}---- <br/><br/> "; 30//the entire transaction will fail if the monitored key has changed since the call to watch
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.