首页 > 解决方案 > 如何使用事件总线在微服务之间进行通信?

问题描述

我正在尝试通过事件总线将数据从一个微服务发送到另一个微服务。但结果仍然是我得到一个空数据,我不明白我做错了什么,请帮忙。

尝试发送数据:

app.get ('/products', async (req , res) => {
    let db = await connect();

    let cursor = await db.collection('posts').find({});
    let doc = await cursor.toArray();
    
    res.json(doc);
    if (doc.insertedCount == 1) {
        res.send({
            status: 'success',
            id: results.insertedId,
        });
    } 
    else {
        res.send({
            status: 'fail',
        });
    }
axios.get('http://localhost:4205/events', {
            type: 'Success',
            data: {
                _id: mongo.ObjectID(id),
                doc,
                postId: req.params.id,
            }
    
        })
});

事件总线:

app.get('/events', async (req, res) => {
    const event = req.body;
    res.json(event);
    axios.get('http://localhost:4202/events', event)
    res.send({status:'OK'})
})

我要获取数据的微服务:

app.get('/events', async (req, res) => {
    
    res.send(req.body)
});

标签: vue.jsevent-handlingmicroservicesevent-bus

解决方案


第一的:

app.get('/products', async (req, res) => {
    try {
        const db = await connect();
        const cursor = await db.collection('posts').find({});
        const doc = await cursor.toArray();

    /*  Below are weird code
      res.json(doc);
      if (doc.insertedCount == 1) {
        res.send({
          status: 'success',
          id: results.insertedId,
        });
      } else {
        res.send({
          status: 'fail',
        });
      }
    */

        axios.post('http://localhost:4205/events', {
            type: 'Success',
            data: {
                id: mongo.ObjectID(id),
                doc,
                postId: req.params.id,
            },
        });

        return res.status(200).send();
  } catch (error) {
    // Here catch and do something with errors;
    console.log(error);
  }
});

第二:

app.post('/events', async (req, res) => {
  try {
    const event = req.body;
    console.log(event);

    // What's mean next line ?
    // res.json(event);

    const response = await axios.post('http://localhost:4202/events', event);
    console.log(response);
    
    return res.status(200).json({ status: 'OK' });
  } catch (error) {
    console.log(error);
  }
});

最后的

app.post('/events', async (req, res) => {
  try {
    console.log(req.body);
    
    return res.status(200).json(req.body);
  } catch (error) {
    console.log(error);
  }
});

推荐阅读