PHP使用Redis常見7種使用場景


   Redis是一個開源的使用ANSI C語言編寫、支持網絡、可基於內存亦可持久化的日志型、Key-Value數據庫,並提供多種語言的API。

 

本篇文章,主要介紹利用php使用Redis,主要的應用場景。

簡單字符串緩存實戰

$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); //輸出數據

簡單隊列實戰

$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 "---- 進隊列成功 ---- 

"; //查看隊列 $strCount = $redis->lrange($strQueueName, 0, -1); echo "當前隊列數據為:
"; print_r($strCount); //出隊列 $redis->lpop($strQueueName); echo "

---- 出隊列成功 ----

"; //查看隊列 $strCount = $redis->lrange($strQueueName, 0, -1); echo "當前隊列數據為:
"; print_r($strCount);

簡單發布訂閱實戰

//以下是 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} ---- 頻道消息推送成功~ 
"; $redis->close(); //以下是 sub.php 文件內容 cli下運行 ini_set('default_socket_timeout', -1); $redis->connect('127.0.0.1', 6379); $strChannel = 'Test_bihu_channel'; //訂閱 echo "---- 訂閱{$strChannel}這個頻道,等待消息推送...----

"; $redis->subscribe([$strChannel], 'callBackFun'); function callBackFun($redis, $channel, $msg) { print_r([ 'redis' => $redis, 'channel' => $channel, 'msg' => $msg ]); }

簡單計數器實戰

$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}。 ---- ";

排行榜實戰

$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}由大到小的排序 ---- 

"; print_r($dataOne); $dataTwo = $redis->ZRANGE($strKey, 0, -1, true); echo "

---- {$strKey}由小到大的排序 ----

"; print_r($dataTwo);

簡單字符串悲觀鎖實戰

解釋:悲觀鎖(Pessimistic Lock), 顧名思義,就是很悲觀。

每次去拿數據的時候都認為別人會修改,所以每次在拿數據的時候都會上鎖。

場景:如果項目中使用了緩存且對緩存設置了超時時間。

當並發量比較大的時候,如果沒有鎖機制,那么緩存過期的瞬間,

大量並發請求會穿透緩存直接查詢數據庫,造成雪崩效應。

public function lock($key = '', $expire = 5) {
    $is_lock = $this->_redis->setnx($key, time()+$expire);
    //不能獲取鎖
    if(!$is_lock){
 //判斷鎖是否過期
 $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
'; echo 'do sth..
'; sleep(5); echo 'success
'; unlock($key); } else { //獲取鎖失敗 echo 'request too frequently
'; }

簡單事務的樂觀鎖實戰

解釋:樂觀鎖(Optimistic Lock), 顧名思義,就是很樂觀。

每次去拿數據的時候都認為別人不會修改,所以不會上鎖。

watch命令會監視給定的key,當exec時候如果監視的key從調用watch后發生過變化,則整個事務會失敗。

也可以調用watch多次監視多個key。這樣就可以對指定的key加樂觀鎖了。

注意watch的key是對整個連接有效的,事務也一樣。

如果連接斷開,監視和事務都會被自動清除。

當然了exec,discard,unwatch命令都會清除連接中的所有監視。

$strKey = 'Test_bihu_age';
$redis->set($strKey,10);
$age = $redis->get($strKey);
echo "---- Current Age:{$age} ---- 

"; $redis->watch($strKey); // 開啟事務 $redis->multi(); //在這個時候新開了一個新會話執行 $redis->set($strKey,30); //新會話 echo "---- Current Age:{$age} ----

"; //30 $redis->set($strKey,20); $redis->exec(); $age = $redis->get($strKey); echo "---- Current Age:{$age} ----

"; //30 //當exec時候如果監視的key從調用watch后發生過變化,則整個事務會失敗

PHP使用Redis常見7種使用場景_PHP-考高分網 (kaotop.com)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM