初始值集发生在服务器上 (\complex\server\index.js):
app.post('/values', async (req, res) => {
const index = req.body.index;
if (parseInt(index) > 40) {
return res.status(422).send('Index too high');
}
redisClient.hset('values', index, 'Nothing yet!');
redisPublisher.publish('insert', index);
pgClient.query('INSERT INTO values(number) VALUES($1)', [index]);
res.send({ working: true });
});
在组件中提交值(\complex\client\src\Fib.js):
handleSubmit = async (event) => {
event.preventDefault();
await axios.post('/api/values', {
index: this.state.index
});
this.setState({ index: '' });
};
工作人员为 Redis 客户端设置值:
sub.on('message', (channel, message) => {
redisClient.hset('values', message, fib(parseInt(message)));
});
sub.subscribe('insert');
但是,当为每个提交的索引列出 Fib.js 组件内的所有值时,组件会收到“Nothing yet!”。
为什么它不会收到计算值? 完整的 repo 协议(protocol)在 https://github.com/ElAnonimo/docker-complex 上
最佳答案
redisClient.hset('values', index, 'Nothing yet!');
是异步的——它需要连接到 Redis、发送消息、等待响应等。< br/>
所以可能发生的是竞争条件,redisPublisher.publish('insert', index);
在 hset
完成之前运行。
我没有检查代码,因此您还需要确保避免在 publish()之后调用
.subscribe()
的类似竞争条件
试试这个:
app.post('/values', async (req, res) => {
const index = req.body.index;
if (parseInt(index) > 40) {
return res.status(422).send('Index too high');
}
redisClient.hset('values', index, 'Nothing yet!', () => redisPublisher.publish('insert', index));
pgClient.query('INSERT INTO values(number) VALUES($1)', [index]);
res.send({ working: true });
});
关于Redis 客户端不会在收到消息后设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52571534/