<?php
namespace app\controller;
use app\BaseController;
use think\facade\Request;
/**
* redis消息队列
* Class RedisQuery
* @package app\controller
*/
class RedisQuery extends BaseController
{
public function getRedis($host = '127.0.0.1', $port = '6379', $password = '', $database = 1)
{
$redis = new \Redis();
if (!$redis->connect($host, $port)) {
die("Redis连接失败:IP或端口有误");
}
if (!empty($password) && !$redis->auth($password)) {
die("Redis连接失败:密码错误");
}
if ($database) {
$redis->select($database);
}
// work中 subscribe 如果一段时间没有接到消息,就会停掉然后停掉,所以加这个语句让其永不超时
$redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
return $redis;
}
// 发布消息
public function register()
{
$name = "name_" . rand(0, 10);
$mobile = rand(1000, 9999);
$redis = $this->getRedis();
// 添加消息
$result = $redis->rpush('register_users', json_encode(array('name' => $name, 'mobile' => $mobile), JSON_UNESCAPED_UNICODE));
if ($result === false) {
die("添加消息队列失败");
}
$redis->close();
echo "发布消息成功";
}
// 消费消息
public function work()
{
$redis = $this->getRedis();
if ($redis->lLen("register_users") > 0) {
$value = $redis->lpop('register_users');
if ($value) {
$userInfo = json_decode($value, true);
echo "新注册用户信息:
";
echo "姓名:" . $userInfo['name'] . "
";
echo "手机号:" . $userInfo['mobile'] . "
";
} else {
echo "出队完成";
}
} else {
echo "没有消息";
}
}
// 查看队列中的消息
public function demo()
{
$redis = $this->getRedis();
$list = $redis->lrange('register_users', 0, -1);
echo "
";
print_r($list);
}
}
发表评论 取消回复