너 바보 아니야

Laravel Redis 广播测试

2019-04-19

附上 [Github] 地址

一、项目搭建
a.安装laravel

composer create-project –prefer-dist laravel/laravel echo

b.配置mysql 数据库

php artisan migrate

c.快速认证

php artisan make:auth

本文仅使用了 redis 的广播驱动 测试环境 win10
二、安装redis 并启动

redis-server.exe

ico原来的样子
测试redis 连接成功
ico原来的样子

a.配置文件 .env 中配置以下代码

1
BROADCAST_DRIVER=redis

b.广播服务提供者 config/app.php 配置文件中 providers 数组中打开注释

1
App\Providers\BroadcastServiceProvider::class,

c.CSRF 令牌[后续视图中添加]

1
<meta name="csrf-token" content="{{ csrf_token() }}">

d.安装 Predis 库

composer require predis/predis

三、安装 Laravel Echo

a.通过 npm 包管理器安装 Echo

npm install
npm install -g laravel-echo-server

b.初始化 laravel-echo-server

laravel-echo-server init

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 是否在开发模式下运行此服务器(y/n) 输入y
? Do you want to run this server in development mode? (y/N)
// 设置服务器的端口 默认 6001 输入 6001就可以了 或者你想要的
? Which port would you like to serve from? (6001)
// 想用的数据库 选择 redis
? Which database would you like to use to store presence channel members? (Use arrow keys)
❯ redis
sqlite
// 这里输入 你的laravel 项目的访问域名
? Enter the host of your Laravel authentication server. (http://localhost)
// 选择 网络协议 http
? Will you be serving on http or https? (Use arrow keys)
❯ http
https
// 您想为HTTP API生成客户端ID/密钥吗 N
? Do you want to generate a client ID/Key for HTTP API? (y/N)
// 要设置对API的跨域访问吗?(y/n)N
Configuration file saved. Run laravel-echo-server start to run server.

设置完成后 项目根目录 下 会生成 laravel-echo-server.json 文件 这里面就是刚才的配置
ico原来的样子
执行命令启动 服务 出现如下 则启动成功

laravel-echo-server start

ico原来的样子

四、频道
频道Channel、PrivateChannel 或 PresenceChannel 的实例。Channel 实例表示任何用户都可以订阅的公开频道,而 PrivateChannels 和 PresenceChannels 则表示需要 频道授权 的私有频道:
a.创建事件

php artisan make:event PublicMessageEvent

文件生成目录 app/Events

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public $message;

/**
* Create a new event instance.
*
* @param User $user
* @param string $message
*/
public function __construct(string $message)
{
$this->message = $message;
}

/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('push');
}

//Laravel 默认会使用事件的类名作为广播名称来广播事件,自定义:
public function broadcastAs()
{
return 'push.message';
}

//想更细粒度地控制广播数据:
public function broadcastWith()
{
return ['message' => $this->message,'status' => 'okok'];
}

// laravel-echo-server 1.5 版本的 需要添加 否则Laravel echo channel listen 不监听事件
public function handle()
{
broadcast(new push());
}

b.添加路由

1
2
3
4
5
6
7
8
use App\Events\PublicMessageEvent;
Route::get('/echo', function () {
return view('echo');
});

Route::get('/push/{message}', function ($message) {
broadcast(new PublicMessageEvent($message));
})

五、前端视图
a.安装 laravel-echo

npm install laravel-echo

编辑 resource/js/bootstrap.js 添加如下代码

1
2
3
4
5
6
import Echo from "laravel-echo"

window.Echo = new Echo({
broadcaster: 'socket.io',
host: window.location.hostname + ':6001'
});

编辑 resource/js/app.js 添加如下代码

1
2
3
4
5
Echo.channel('push')
.listen('.push.message', (e) => {
alert(e.message)
console.log(e);
});

创建 echo.blade.php head 中加上

1
2
3
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="//{{ Request::getHost() }}:6001/socket.io/socket.io.js"></script>
<script src="/js/app.js"></script>

编译 js 文件

npm run watch

浏览器访问 项目域名 /echo
浏览器访问 项目域名 /push/这是一个测试广播[what can i say]
echo 页面 会自动弹出
ico原来的样子
ico原来的样子
ico原来的样子
到这 广播 发布到公共频道就完成了


私有频道 PrivateChannel

php artisan make:event PrivateMessageEvent

PrivateMessageEvent 中 写入 以下内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public $message;
public $user;

/**
* Create a new event instance.
*
* @param User $user
* @param string $message
*/
public function __construct(User $user, string $message)
{
$this->user = $user;
$this->message = $message;
}

/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('privatePush.' . $this->user->id);
}

//想更细粒度地控制广播数据:
public function broadcastWith()
{
return ['message' => $this->message,'status' => 'okok'];
}

添加发布广播到私有频道 触发路由 routes/web 测试时记得新增下用户

1
2
3
4
5
Route::get('/privatePush/{message}/{id}', function ($message, $id) {
$user = \App\User::find($id);
if (empty($user)) return '无此用户';
broadcast(new PrivateMessageEvent($user, $message));
});

echo.blade.php 中加入

1
2
3
4
5
<script>
@if(!empty(Auth::user()))
window.id = "{{Auth::user()->id}}"
@endif
</script>

app.js

1
2
3
4
5
Echo.private('privatePush.' + window.id)
.listen('PrivateMessageEvent', (e) => {
alert('qweqwe')
console.log(e);
});

  • Notice
    安静,安静一下 Enjoy it ~
使用支付宝打赏
使用微信打赏

欢迎点击上方按钮对我打赏,谢谢你给我吃糖果