如何从我的ReactJS应用程序连接到RabbitMQ?

时间:2019-11-05 19:41:33

标签: reactjs rabbitmq stompjs

我无法连接到RabbitMQ实例,因此找不到很好的教程或指南。我可以通过

连接到RabbitMQ Websocket
var ws = new WebSocket('ws://localhost:15674/ws')

但是现在我不知道如何使用我的凭据连接到群集。我还需要使用/exchange/myExchange/routingKey这样的队列中的消息。通过使用带有以下代码的RxStompService,我可以在有角度的应用程序中轻松做到这一点


  rxStompService.configure({
          brokerURL: `ws://localhost:15674/ws`,
          connectHeaders: {
            login: 'guest',
            passcode: 'guest'
          },
          heartbeatIncoming: 0, // Typical value 0 - disabled
          heartbeatOutgoing: 20000, // Typical value 20000 - every 20 seconds
          reconnectDelay: 200,
          debug: (msg: string): void => {
            console.log(new Date(), msg);
          }
        })

  this.exchange = 'myExchange'
  this.routingKey = 'routingKey'
  this.headers ={
    'x-queue-name': 'myQueue',
    'durable': 'true',
    'auto-delete': 'false'
  }

  ngOnInit() {
    this.rxStompService.watch(`/exchange/${this.exchange}/${this.routingKey}`, this.headers ).subscribe((message: Message) => {
     this.user = new User(JSON.parse(message.body))
    });
  }

如何通过我的React应用执行同样的操作?

1 个答案:

答案 0 :(得分:0)

我能够使用stompjs连接并订阅队列。

import Stomp from 'stompjs'


export function connectRabbit(){

let stompClient

    var ws = new WebSocket('ws://localhost:15674/ws')

    const headers = {
        'login': 'guest',
        'passcode': 'guest',
        'durable': 'true',
        'auto-delete': 'false'
    }
    stompClient = Stomp.over(ws)

    stompClient.connect(headers , function(frame){
                console.log('Connected')
               const subscription = stompClient.subscribe('/queue/myQueue', function(message){
                   console.log(message)
               })
    })

}