redis使用管道pipeline提升批量操作性能(php演示)

Posted 郁冬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redis使用管道pipeline提升批量操作性能(php演示)相关的知识,希望对你有一定的参考价值。

Redis是一个TCP服务器,支持请求/响应协议。 在Redis中,请求通过以下步骤完成:

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

如果需要一次执行多个redis命令,以往的方式需要发送多次命令请求,有redis服务器依次执行,并返回结果,

为了解决此类问题,设计者设计出了redis管道命令:

  • 客户端可以向服务器发送多个请求,而不必等待回复,并最终在一个步骤中读取回复,从而大大增加了协议性能

做了测试,使用pipeline的时长为603.4ms,不使用则为10716.9ms,差距有18倍之多!

以下是代码:

<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Redis;

class LessonsController extends Controller
{
    public function showProfile()
    {

        $this->G(‘t‘);
//        redis::pipeline();
        for ($i=0; $i < 100000 ; $i++) {
            redis::set("test_{$i}", pow($i, 2));
            redis::get(‘test_{$i}‘);
        }
        redis::exec();
        $this->G(‘t‘,‘r‘);
    }

    public function G($start,$end=‘‘,$dec=4)
    {
        static $_info = array();
        if (!empty($end))
        {
            if(!isset($_info[$end])) $_info[$end] = microtime(TRUE);
            $sconds = number_format(($_info[$end]-$_info[$start]), $dec) * 1000;
            echo "{$sconds}ms<br />";
        }
        else
        {
            $_info[$start] = microtime(TRUE);
        }
    }
}

 

以上是关于redis使用管道pipeline提升批量操作性能(php演示)的主要内容,如果未能解决你的问题,请参考以下文章

使用Redis管道提升性能

使用Redis管道提升性能

redis性能提升之pipeline

使用管道(PipeLine)和批量(Batch)操作

Redis大幅性能提升之Batch批量读写

redis之管道——pipeline