1,892   Redis

一,业务背景:

1,有时候并发业务量过大,导致服务器无法承受,可以考虑把并发请求放进队列,然后再一个个执行,避免并发过大出现的各种问题。

2,Redis的List可以实现队列机制,先push数据到list中,然后再一个个pop出来处理,达到排队的效果。

 

二,具体实现:

1,入队操作,每隔三秒插入一条数据到队列

$redis->delete('result_list');
while (true) {
	try {   
		$data = 'test_'.date('Y-m-d H:i:s');
		echo date('Y-m-d H:i:s').' 数据进入队列:'.$data,"\n";
  		$result = $redis->lPush('result_list', $data); 
	} catch (Exception $e) {   
		var_dump($e->getMessage());   
	}   
	$seconds = 3;
	echo date('Y-m-d H:i:s').' 等待'.$seconds.'秒',"\n";
	sleep($seconds);
}

2,出队处理,阻塞读取队列数据,超时时间为10秒,循环读取队列

while (true) {
	try {   
		echo date('Y-m-d H:i:s').' 读取队列数据',"\n";
		$result = $redis->brPop('result_list', 10);
		echo date('Y-m-d H:i:s').' 读到数据为:',"\n";
		var_dump($result);
	} catch (Exception $e) {   
		var_dump($e->getMessage());   
	}  
	echo date('Y-m-d H:i:s').' 循环读取',"\n";

}

 

三,测试结果:

1,入队操作,每隔三秒插入一条数据到队列

2015-05-22 10:51:17 数据进入队列:test_2015-05-22 10:51:17
2015-05-22 10:51:17 等待3秒
2015-05-22 10:51:20 数据进入队列:test_2015-05-22 10:51:20
2015-05-22 10:51:20 等待3秒
2015-05-22 10:51:23 数据进入队列:test_2015-05-22 10:51:23
2015-05-22 10:51:23 等待3秒


2,出队处理,阻塞读取队列数据,超时时间为10秒,循环读取队列

chenyunhui@ubuntu:/mnt/hgfs/ShareFolder/web/click$ php queue.php 
2015-05-22 10:51:00 读取队列数据
2015-05-22 10:51:10 读到数据为:
array(0) {
}
2015-05-22 10:51:10 循环读取
2015-05-22 10:51:10 读取队列数据
2015-05-22 10:51:17 读到数据为:
array(2) {
  [0]=>
  string(11) "result_list"
  [1]=>
  string(24) "test_2015-05-22 10:51:17"
}
2015-05-22 10:51:17 循环读取
2015-05-22 10:51:17 读取队列数据
2015-05-22 10:51:20 读到数据为:
array(2) {
  [0]=>
  string(11) "result_list"
  [1]=>
  string(24) "test_2015-05-22 10:51:20"
}
2015-05-22 10:51:20 循环读取
2015-05-22 10:51:20 读取队列数据
2015-05-22 10:51:23 读到数据为:
array(2) {
  [0]=>
  string(11) "result_list"
  [1]=>
  string(24) "test_2015-05-22 10:51:23"
}
2015-05-22 10:51:23 循环读取




Leave a Reply

Your email address will not be published. Required fields are marked *