redis性能提升之pipeline

时间:2023-03-08 17:45:35

1、以前正常使用过程

客户端向服务器发送查询,并从套接字读取,通常以阻塞的方式,用于服务器响应。

服务器处理命令并将响应发送回客户端。

也就是每个命令都会有一来以往的过程

2、管道的意义

如果能将连续执行的redis命令在操作完成后统一返回,就可以减少连接数,从来减少延迟时间,那么管道也就产生了。

管道的基本含义是,客户端可以向服务器发送多个请求,而不必等待回复,并最终在一个步骤中读取回复。

3.参数说明:

Redis::MULTI或Redis::PIPELINE. 默认是 Redis::MULTI

Redis::MULTI:将多个操作当成一个事务执行

Redis::PIPELINE:让(多条)执行命令简单的,更加快速的发送给服务器,但是没有任何原子性的保证

测试代码1:

<?php
set_time_limit(0);
ini_set('memory_limit', '1024M'); $redis = new Redis(); G('1');
$redis->connect('127.0.0.1');
//不具备原子性 ,管道
$redis->pipeline();
for ($i = 0; $i < 100000; $i++) {
$redis->set("test_{$i}", pow($i, 2));
$redis->get("test_{$i}");
}
$redis->exec();
$redis->close();
G('1', 'e'); G('2');
$redis->connect('127.0.0.1');
//事物具备原子性
$redis->multi();
for ($i = 0; $i < 100000; $i++) {
$redis->set("test_{$i}", pow($i, 2));
$redis->get("test_{$i}");
}
$redis->exec();
$redis->close();
G('2', 'e'); //普通
G('3');
$redis->connect('127.0.0.1');
//事物具备原子性
for ($i = 0; $i < 100000; $i++) {
$redis->set("test_{$i}", pow($i, 2));
$redis->get("test_{$i}");
}
$redis->close();
G('3', 'e'); function G($star, $end = '')
{
static $info = array();
if (!empty($end)) {
$info[$end] = microtime(true);
$sconds = $info[$end] - $info[$star];
echo $sconds, "ms" ;
echo PHP_EOL;
} else {
$info[$star] = microtime(true);
}
}

结果输出:

0.85941696166992ms 14.938266992569ms 15.121881961823ms

测试代码2:

<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$pipe = $redis->multi(Redis::PIPELINE);
for ($i = 0; $i < 3; $i++) {
$key = "key::{$i}";
print_r($pipe->set($key, str_pad($i, 2, '0', 0)));
echo PHP_EOL;
print_r($pipe->get($key));
echo PHP_EOL;
}
$result = $pipe->exec();
echo "<pre>";
var_dump($result);

输出结果:

Redis Object ( ) Redis Object ( ) Redis Object ( ) Redis Object ( ) Redis Object ( ) Redis Object ( )

array(6) {

[0]=>

bool(true)

[1]=>

string(2) "00"

[2]=>

bool(true)

[3]=>

string(2) "01"

[4]=>

bool(true)

[5]=>

string(2) "02"

}