egg
egg copied to clipboard
egg-redis 订阅
- Node Version:v7.9.0
- Egg Version:1.8.0
- Plugin Name:
- Plugin Version:
- Platform:win10
- Mini Showcase Repository: 我再使用egg_redis 订阅消息后发现redis 连接被用来subscriber了。没法set操作了。
module.exports = app => {
app.beforeStart(function*() {
// 如果启用了redis;
if (app.config.redis.app) {
const subscribe = yield app.redis.subscribe('news', 'music');
console.log('subscribe redis \t' + subscribe);
app.redis.on('message', function (channel, message) {
if (channel === 'news') {
console.log('news channel:' + message)
} else if (channel === 'music') {
console.log('music channel:' + message)
}
});
}
setTimeout(() => {
// 程序会在这里报错;Connection in subscriber mode, only subscriber commands may be used
app.redis.set('foo', 'foo');
}, 1000)
});
}
程序会在setTimeout 哪里报错,放到service里面也报错。 Connection in subscriber mode, only subscriber commands may be used 我如何在手工新建一个redis连接,用来set 操作呢?
这就是 Redis 预期的行为
Once the client enters the subscribed state it is not supposed to issue any other commands, except for additional SUBSCRIBE, PSUBSCRIBE, UNSUBSCRIBE and PUNSUBSCRIBE commands.
你需要启动两个 Redis 连接,其中一个用来订阅。
egg-redis 启动两个连接的方式很简单,在 config 里指定
config.redis = {
clients: {
client1: {
host: 'localhost',
port: 6379,
db: 0,
},
client2: {
host: 'localhost',
port: 6379,
db: 0,
},
}
}
然后使用的时候是 app.redis.get('client1').set()。
太感谢你了。
public async publish() {
await this.app.redis.get('client1').subscribe('news', 'music');
await this.app.redis.get('client2').publish('music', 'hong');
await this.app.redis.get('client2').publish('news', 'zheng');
const a = this.app.redis.get('client1').on('message', (channel, message) => {
return [channel, message];
});
console.log(a);
this.ctx.body = {
msg: a,
};
}
您好,楼主,能看下您的发布订阅的代码么?我不会写。。。。或者请您指点一下,应该怎么写啊? @nxycdl 谢谢
//app.ts
import { Application } from 'egg';
module.exports = (app: Application) => {
app.beforeStart(() => {
if (app.config.redis.app) {
app.redis.get('client1').subscribe('news', 'it', (err, result) => {
if (err) {
throw err;
}
console.log(result, 'psubscribe');
});
app.redis.get('client1').on('message', (channel, message) => {
console.log(message, channel);
// console.log(message, 'music');
});
}
});
};
//controller/XX.ts
public async publish() {
// await this.app.redis.get('client1').subscribe('news', 'music');
await this.app.redis.get('client2').publish('news', 'hong', (err, result) => {
if (err) {
throw err;
}
console.log(result, 'client2 news');
});
await this.app.redis.get('client2').publish('it', 'zheng', (err, result) => {
if (err) {
throw err;
}
console.log(result, 'client2 it');
});
// const a = this.app.redis.get('client1').on('message', (channel, message) => {
// return [channel, message];
// });
// console.log(a);
await this.app.redis.get('client2').set('zheng', 'bar');
this.ctx.body = {
msg: 'ok',
};
}