Redis Common seven usage scenarios (PHP combat)

Source: Internet
Author: User

Edis is an open source API that is written in ANSI C, supports the network, can be persisted in memory, key-value databases, and provides multiple languages.

This article, mainly introduces the use of Redis Common Application scenario PHP combat.

Simple string Cache Combat

$redis->connect(‘127.0.0.1‘, 6379);$strCacheKey  = ‘Test_bihu‘;//SET 应用$arrCacheData = [    ‘name‘ => ‘job‘,    ‘sex‘  => ‘男‘,    ‘age‘  => ‘30‘];$redis->set($strCacheKey, json_encode($arrCacheData));$redis->expire($strCacheKey, 30);  # 设置30秒后过期$json_data = $redis->get($strCacheKey);$data = json_decode($json_data);print_r($data->age); //输出数据//HSET 应用$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); //输出数据

Simple Queue Combat

$redis->connect(‘127.0.0.1‘, 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 "---- 进队列成功 ---- <br /><br />";//查看队列$strCount = $redis->lrange($strQueueName, 0, -1);echo "当前队列数据为: <br />";print_r($strCount);//出队列$redis->lpop($strQueueName);echo "<br /><br /> ---- 出队列成功 ---- <br /><br />";//查看队列$strCount = $redis->lrange($strQueueName, 0, -1);echo "当前队列数据为: <br />";print_r($strCount);

Simple release Subscription Combat

//以下是 pub.php 文件的内容 cli下运行ini_set(‘default_socket_timeout‘, -1);$redis->connect(‘127.0.0.1‘, 6379);$strChannel = ‘Test_bihu_channel‘;//发布$redis->publish($strChannel, "来自{$strChannel}频道的推送");echo "---- {$strChannel} ---- 频道消息推送成功~ <br/>";$redis->close();
//以下是 sub.php 文件内容 cli下运行ini_set(‘default_socket_timeout‘, -1);$redis->connect(‘127.0.0.1‘, 6379);$strChannel = ‘Test_bihu_channel‘;//订阅echo "---- 订阅{$strChannel}这个频道,等待消息推送...----  <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‘;//设置初始值$redis->set($strKey, 0);$redis->INCR($strKey);  //+1$redis->INCR($strKey);  //+1$redis->INCR($strKey);  //+1$strNowCount = $redis->get($strKey);echo "---- 当前数量为{$strNowCount}。 ---- ";

Leaderboard Combat

$redis->connect(‘127.0.0.1‘, 6379);$strKey = ‘Test_bihu_score‘;//存储数据$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}由大到小的排序 ---- <br /><br />";print_r($dataOne);$dataTwo = $redis->ZRANGE($strKey, 0, -1, true);echo "<br /><br />---- {$strKey}由小到大的排序 ---- <br /><br />";print_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 query the database directly through the cache, creating an avalanche effect.

/** * Get lock * @param  string   $key     Lock ID * @param  int     $expire lock expiry time * @return Boole An */public function lock ($key = ", $expire = 5) {    $is _lock = $this->_redis->setnx ($key, Time () + $expir e);    //cannot get lock    if (! $is _lock) {       //determine if lock expiration         $lock _ti me = $this->_redis->get ($key);        //lock expired, delete lock, re-fetch       &NBSP;IF (Time () > $lock _time) {      & nbsp    unlock ($key);             $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 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,10);$age = $redis->get($strKey);echo "---- Current Age:{$age} ---- <br/><br/>";$redis->watch($strKey);// 开启事务$redis->multi();//在这个时候新开了一个新会话执行$redis->set($strKey,30);  //新会话echo "---- Current Age:{$age} ---- <br/><br/>"; //30$redis->set($strKey,20);$redis->exec();$age = $redis->get($strKey);echo "---- Current Age:{$age} ---- <br/><br/>"; //30//当exec时候如果监视的key从调用watch后发生过变化,则整个事务会失败

Redis Common seven usage scenarios (PHP combat)

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.