Redis 客户端不会在收到消息后设置值

标签 redis node-redis

初始值集发生在服务器上 (\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/

相关文章:

asp.net-mvc-4 - 如何在主机服务器中配置多个 Redis 端口

memory-management - Redis - 如何存储我的数据?

javascript - 如何使 const 变量可用于其他文件

javascript - Redis递归:超出最大调用堆栈大小

python - Django 中的 Redis : redis. exceptions.ConnectionError : Error -2 connecting to 127. 0.0.1 :20789:0. 名称或服务未知

redis - ServiceStack Redis 客户端的非通用 Store 方法或非通用 GetTypedClient

redis - 调用 PUBSUB 命令?

node-redis - node_redis - 如何获取 key 的 TTL?

redis如何在1个查询中组合多个命令

redis - 为什么 Redis 没有 LINCR?