这是我的 Routes.php
Route::get('hello1',function(){
Redis::publish('test-channel', json_encode(['foo' => 'bar']));
});
这是我的 app.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var Redis = require('ioredis');
var redis = new Redis();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
redis.subscribe('test-channel', function () {
console.log('Redis: test-channel subscribed');
});
redis.on('message', function(channel, message) {
console.log('Redis: Message on ' + channel + ' received!');
console.log(message);
message = JSON.parse(message);
io.emit(channel, message.payload)
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(6379, function(){
console.log('listening on *:6379');
});
我的 index.html
<!doctype html>
<html>
<head>
<title>Socket.IO</title>
</head>
<body>
<ul id="messages">
<li>Hardcoded Message</li>
</ul>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
socket.on("test-channel", function(message) {
console.log(message);
$('#messages').append($('<li>').text(message));
});
</script>
</body>
</html>
现在每当运行 php artisan redis:subscribe 或 hello1 路由时,我都会收到类似这样的错误,
ConnectionException in AbstractConnection.php line 146: Error while reading line from the server. [tcp://localhost:6379]
最佳答案
Redis 默认监听端口 6379,并且您已将 http 服务器设置为监听同一端口。这行不通,您在尝试运行 Node 应用程序时不会收到错误消息吗?如果您没有收到错误,则 redis 很可能根本没有运行或正在监听另一个端口。
如果您的 redis 实例正在监听另一个端口,laravel 将尝试连接到端口 6379 上的 redis 并将命中 Node 服务器,因此无法连接到 redis,因为没有 redis 但 Node http 服务器正在监听在这个端口上。
如果您的 redis 实例正在监听另一个端口,并且您在 laravel 配置中更改了它,则必须通过传递端口来更改将 ioredis 连接到 redis 的方式:
例如
var redis = new Redis(6380)
参见 github page有关将 ioredis 连接到 redis 的更多详细信息。
作为结论,确保
- Redis 正在运行
- 您的 http 服务器正在监听与 redis 不同的端口
- 您的 config/database.php 和 config/broadcast.php (laravel) 中的 redis 连接设置以及 server.js 文件中的 Node 设置正确
请注意,http 服务器不是正在连接到 redis,ioredis 是。
关于php - Laravel 5.1 使用 Redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31302580/