laravel redis 订阅 发布 (sub/pub)

* 配置redis扩展

https://blog.csdn.net/fareast_mzh/article/details/81463749

用php -S 0.0.0.0:8090 -t public 这种web服务, redis连接失败。我用的xampp, extra/httpd-vhost.conf配置

* composer安装redis连接的组件

composer require predis/predis

查看composer.json, predis安装好了

 "predis/predis": "^1.1"

* 启动redis-server

D:\bin\redis-server D:\bin\redis.windows.conf

* 配置laravel框架根目录的环境变量 .env

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=myredispassword
REDIS_PORT=6379

* config/database.php

    'redis' => [

        'client' => 'predis',

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', 'myredispassword'),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
        ],

    ],

* config\cache.php

'default' => env('CACHE_DRIVER', 'redis')

以上的配置参考 https://laravel.com/docs/5.6/redis#configuration

* app\Http\Controllers\UserController.php

  发布消息 触发事件 (这个应该放在注册handler后面的)

<?php
namespace App\Http\Controllers;

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

class UserController extends Controller {
    /**
     * Show the profile for the given user.
     *
     * @param  int  $id
     * @return Response
     */
    public function showProfile($id) {
        $user = Redis::get("user:profile:".$id);
        return $user;
    }

    public function getProfile(Request $request) {
        $user = Redis::get("user:profile:".$request->get("id"));
        return $user;
    }

    public function publish() {
        $msg = \json_encode(['foo' => 'bar']);
        return [
            'code' => Redis::publish('test-channel', $msg),
            'msg' => $msg
        ];
    }

    public function test() {
        Redis::pipeline(function($pipe) {
            for ($i = 0; $i < 100; $i++) {
                $pipe->set("key:$i", $i);
            }
        });
    }
}

* app\Console\Commands\RedisSubscribe.php

  设定消息处理listener函数

<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class RedisSubscribe extends Command {
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'redis:subscribe';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = "Subscribe to a Redis channel";

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle() {
        Redis::subscribe(['test-channel'], function($message) {
            echo $message;
        });
    }

}

* app\Console\Kernel.php

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\RedisSubscribe::class,

    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule) {
        // $schedule->command('inspire')->hourly();
        $schedule->call(function() {
            // ...
        })->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands() {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}

* 配置路由

 routes\web.php

<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

// Route::get('/user/profile/{$id}', "UserController@showProfile");
Route::get('/user/profile', "UserController@getProfile");
Route::get('/user/publish', "UserController@publish");
Route::get('/user/test', "UserController@test");

* 测试

** 从终端订阅消息

php artisan redis:subscribe -v

** 从浏览器发布消息

http://127.0.0.1:8090/user/publish

** 结果

浏览器显示

{"code":1,"msg":"{\"foo\":\"bar\"}"}

终端

E:\code\php\blog>php artisan redis:subscribe -v
{"foo":"bar"}{"foo":"bar"}

浏览器每刷新一次 终端打印一次

* Wildcard Subscriptions  通配符订阅  批量订阅

app\Console\Commands\RedisSubscribe.php

修改handle方法

    public function handle()
    {
        /*
        Redis::subscribe(['test-channel'], function ($message) {
            echo $message;
        });
        */
        Redis::psubscribe(['test-*'], function($msg) {
            echo 'handling Wildcard Subscriptions: '.$msg;
        });
    }

> php artisan redis:subscribe

浏览器再访问 http://127.0.0.1:8090/user/publish

终端输出:

handling Wildcard Subscriptions: {"foo":"bar"}

猜你喜欢

转载自blog.csdn.net/fareast_mzh/article/details/83105713