php 消息队列_基于Redis、PHP实现的简单消息队列

179053ac476e81d7843eff81b6ee0b67.png
基于Redis实现的简单消息队列​www.woojean.com
93868e6ed584a5ccdbd9798a0d9d6e46.png

源代码

代码见这里:https://github.com/woojean/RedisQueue

数据流

a9d4aaee4679c6bcb83c9842d26d1205.png

Demo

Add task

<?php

// 队列配置
$queueName = 'myqueue';
$redisConfig = [
  'host' => '127.0.0.1',
  'port' => '6379',
  'index' => '0'
];

// 添加任务
$data = [
 'k1' => 'v1',
 'k2' => 'v2',
];

echo "Queue name: " . $queueName . "n";

try {
  // create queue
  $redisQueue = new RedisQueue($queueName, $redisConfig);

  // add to queue
  $index = $redisQueue->add($data);

  echo "Data index: " . $index . "n";  // index of added data

} catch (RedisQueueException $e) {
  echo $e->getMessage();
}

处理任务

<?php

  // 队列配置
  $queueName = 'myqueue';
  $redisConfig = [
    'host' => '127.0.0.1',
    'port' => '6379',
    'index' => '0'
    ];

  echo "Queue name: " . $queueName . "n";

  try {
    // create queue
    $redisQueue = new RedisQueue($queueName, $redisConfig);

    // fetch from queue
    $data = $redisQueue->get();
    echo "Fetched data:n";
    var_dump($data);

    // get the index of current data
    echo "Current Index:";
    $currentIndex = $redisQueue->getCurrentIndex();
    var_dump($currentIndex);
    echo $currentIndex;


    /* ... */
    $success = True;  //  process result
    //$success = False;  //  process result
    /* ... */


    if ($success) {  // success
      $ret = $redisQueue->remove();
      if (!empty($ret)) {
        echo "nData removed !";
      }
    } else { // failed
      echo "nRollback current data";
      $redisQueue->rollback();  // if retry times up to max, the index will be transfer to blocked list
    }
  } catch (RedisQueueException $e) {
    echo $e->getMessage();
  }

其他参数

  • $queueName
  • $redisConfig Redis connect config.
  • $retryTimes If the task handle failed,and up to retryLimit ,the task will be transfer to block task.
  • $waitTime If there is no more task to handle, the ‘get’ action will be block.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值