【问题标题】:Redis client won't set values upon message receivedRedis 客户端不会在收到消息后设置值
【发布时间】:2019-03-05 09:47:11
【问题描述】:

初始值集发生在服务器上 (\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: '' });
  };

worker 为 Redis 客户端设置值:

sub.on('message', (channel, message) => {
  redisClient.hset('values', message, fib(parseInt(message)));
});
sub.subscribe('insert');

但是,当为每个提交的索引列出 Fib.js 组件内的所有值时,组件会收到“还没有!”。

为什么它不接收计算值? 完整的 repo 在https://github.com/ElAnonimo/docker-complex

【问题讨论】:

    标签: redis node-redis


    【解决方案1】:

    redisClient.hset('values', index, 'Nothing yet!');是异步的——它需要连接Redis,发送消息,等待响应等
    所以可能会发生竞争条件,redisPublisher.publish('insert', index);hset 完成之前运行。

    我没有查看代码,因此您还需要确保避免在 subscribe() 之后调用 publish() 的类似竞争条件。

    试试这个:

    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 });
    });
    

    【讨论】:

    • 谢谢。没有解决我的问题。我尝试将setTimeout(() => sub.subscribe('insert'), 3000); 添加到工作代码中,也没有想要的结果。
    • 嘿@ElAnonimo,你找到解决方案了吗?
    【解决方案2】:

    问题在于您的docker-compose.yml 文件。 您必须为工作容器指定环境变量并指定 redis hostport(就像您为服务器容器指定的方式一样):

    worker:
        environment:
          - REDIS_HOST=redis
          - REDIS_PORT=6379
    

    【讨论】:

    • @Karpukhin Olexiy 试试这个解决方案
    猜你喜欢
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多