1. 程式人生 > 實用技巧 >redis常用操作

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); //輸出資料


$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);


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


/**
 * 獲取鎖
 * @param  String  $key    鎖標識
 * @param  Int     $expire 鎖過期時間
 * @return Boolean
 */
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;
}

/**
 * 釋放鎖
 * @param  String  $key 鎖標識
 * @return Boolean
 */
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);
} else { //獲取鎖失敗
	echo 'request too frequently<br>';
}


$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