【问题标题】:NodeJS API with Kafka back-end带有 Kafka 后端的 NodeJS API
【发布时间】:2020-06-05 20:54:07
【问题描述】:

我想构建一个基于 NodeJS 的 API,它以 pub-sub 范式为后盾,例如卡夫卡。这是我想做的事情的骨架。

const express = require('express')
const serverApp = express()
serverApp.get('/book/:bookId', (req, res) => {
    producer.send(JSON.stringify({
        action: 'get',
        message: req.params.bookId
    }))
    consumer.on('message', (data) => {
        res.status(200).send(JSON.parse(data))
    })
})

使用上面的选项,第一次调用有效,但随后的调用继续失败,并显示ERR_HTTP_HEADERS_SENT

consumer.on 保留在serverApp.get 之外需要协调reqres

如何实现这样的 API?

【问题讨论】:

  • 您每次都需要退订...

标签: node.js rest apache-kafka publish-subscribe api-design


【解决方案1】:

例如作为骨架

const express = require('express')
const serverApp = express()

const responses = Object.create(null);

consumer.on('message', (data) => {
    const result = JSON.parse(data)
    const res = responses[result.replyId]
    res.status(200).send(result)
});

serverApp.get('/book/:bookId', (req, res) => {

    const replyId = Math.random().toString(36).substr(2);    
    responses[replyId] = res;

    producer.send(JSON.stringify({
        action: 'get',
        replyId,
        message: req.params.bookId
    }))
})

【讨论】:

  • 当我尝试这个时,sunstr 应该是 substrreplyId 应该有一个密钥?
  • replyId 只是一些独特的 ID。删除处理程序必须将其返回。
  • 是的,但是,在您的JSON.stringify 中,replyId 应该是键值对,对吧?
猜你喜欢
  • 2015-10-31
  • 2021-11-21
  • 2016-10-20
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
相关资源
最近更新 更多