Vue Electron与RabbitMQ发送接收消息

参考资料:

electron-vue 跨平台桌面应用开发实战教程
electron-vue 中文文档
Electron-vue 开发实战
Electron 12.0 官方文档

搭建项目

vue create electron_rabbitmq
cd electron_rabbitmq
vue add electron-builder
npm i amqplib -S

主进程中初始化 RabbitMQ模块

在src目录下新建文件 mainProcesses/rabbitmq.js
目录结构
在主进程中与RabbitMQ进行通信, 该模块主要完成以下功能:

  • 1.连接RabbitMQ服务器,并创建生产者和消费者
const amqp = require('amqplib')
const serverConfig = {
  protocol: 'amqp',
  hostname: '192.168.1.251',
  port: 5672,
  username: 'xyang',
  password: '123456',
  vhost: process.env.NODE_ENV !== 'production' ? '/dev' : '/prod'
}
amqp.connect(serverConfig).then(
      conn => {
        console.log('创建连接成功')
        conn.createChannel().then(
          ch => {
            console.log('创建Channel成功')
            //连接交换机
            ch.assertExchange('api', 'topic',{durable:true}).then(function(ex) {
             	//连接队列
            	ch.assertQueue("topic").then(function(q) {    
            	 	// 交换机bind队列
            	 	//			   队列     交换机     Rounting KEY   arguments
            		ch.bindQueue(q.queue, ex.exchange, "topic", {'x-match': 'any'}); 
					ch.publish(ex.exchange, ’topic', Buffer.from(JSON.stringify(msgObj)));    
            	})
            })
            // 设置消费者
            ch.consume('topic',
              function(msg) {
                console.log(JSON.parse(msg.content))
              },
              {
                noAck: true
              }
            )   
          },
          err => {
            console.log('创建Channel 错误:' + err)
          }
        )
      },
      err => {
        console.log('连接MQ Server 错误:' + err)
      }
    )
  }
  • 2.注册消息发送器,当渲染进程需要发送消息时,通过 ipcRenderer 发送消息
// 主进程注册
ipcMain.handle('SEND_MQ_ORDER_MESSAGE', async (event, msgObj) => {})

//渲染进程要发送消息的时候调用上面的Handle
ipcRenderer.invoke('SEND_MQ_MESSAGE', 'send message content')
  • 3.推送消息到Windows 通知栏
let notification = new Notification({
   title: title, // 通知的标题, 将在通知窗口的顶部显示
   body: content, // 通知的正文文本, 将显示在标题或副标题下面
   silent: true // 在显示通知时是否发出系统提示音
})
notification.show()
  • 4.当通知栏被点击的时候,主进程通知到渲染进程
notification.on('click', e => {
     notification.close()
     // 通知主进程通知了被点击
     webContents.send('ON_NOTIFICATION_CLICK', {
       title: e.sender.title,
       body: e.sender.body
     })
 })
 
// 渲染进程接收 主进程通知
ipcRenderer.on('ON_NOTIFICATION_CLICK', (event, message) => {
      window.alert('通知点击:' + message.title)
})

完整代码

const amqp = require('amqplib')
const { ipcMain, Notification } = require('electron')

const serverConfig = {
  protocol: 'amqp',
  hostname: '192.168.1.251',
  port: 5672,
  username: 'xyang',
  password: '123456',
  vhost: process.env.NODE_ENV !== 'production' ? '/dev' : '/prod'
}

module.exports = {
	init(win) {
		// 消息处理器
		function receivedCallBack(msg) {
			let notification = new Notification({
		        title: msg.title, // 通知的标题, 将在通知窗口的顶部显示
		        body: msg.content, // 通知的正文文本, 将显示在标题或副标题下面
		        silent: true // 在显示通知时是否发出系统提示音
		    })
			notification.show()
			// 任务栏闪烁,当获取焦点后取消闪烁
	      	win.once('focus', () => win.flashFrame(false))
	      	win.flashFrame(true)
	      	// 通知主进程
	      	win.webContents.send('ON_NEW_NOTIFICATION', {msg: msg});
	      	// 被点击之后通知渲染进程
		    notification.on('click', e => {
		    	notification.close()
		        console.log(e)
		        win.webContents.send('ON_NOTIFICATION_CLICK', {
		          title: e.sender.title,
		          body: e.sender.body,
		          msg: msg
		        })
		    })
			      	
		} 
		// 链接MQ
		amqp.connect(serverConfig).then(
	      conn => {
	        console.log('创建连接成功')
	        conn.createChannel().then(
	          ch => {
	            console.log('创建Channel成功')
	            //连接交换机
	            ch.assertExchange('api', 'topic',{durable:true}).then(function(ex) {
	             	//连接队列
	            	ch.assertQueue("topic").then(function(q) {    
	            	 	// 交换机bind队列
	            	 	//			   队列     交换机     Rounting KEY   arguments
	            		ch.bindQueue(q.queue, ex.exchange, "topic", {'x-match': 'any'});
	            		// 注册消息发送器 
	            		ipcMain.handle('SEND_MQ_ORDER_MESSAGE', async (event, msgObj) => {
							ch.publish(ex.exchange, ’topic', Buffer.from(JSON.stringify(msgObj))); 
						))
	            	})
	            })
	            // 设置消费者
	            ch.consume('topic',
	              function(msg) {
	                receivedCallBack(JSON.parse(msg.content))
	              },
	              {
	                noAck: true
	              }
	            )   
	          },
	          err => {
	            console.log('创建Channel 错误:' + err)
	          }
	        )
	      },
	      err => {
	        console.log('连接MQ Server 错误:' + err)
	      }
	    )
	  }
	 
	}
}

初始化RabbitMQ

background.js 中加入:

const rabbitmq = require('./mainProcesses/rabbitmq')

app.on('ready', async () => {
  createWindow()
  // win 为创建的窗口,定义为全局变量
  rabbitmq.init(win)
})

App.vue页面监听

<template>
  <div id="app">
    <p>标题: <input type="text " v-model="title" /></p>
    <p>内容: <input type="text " v-model="content" /></p>
    <p><button @click="sendMsg">发送消息</button></p>
  </div>
</template>
const { ipcRenderer } = window.require('electron')
export default {

  name: 'App',
  data() {
    return {
      title: '',
      content: ''
    }
  },
  created() {
  	// 注册 
    ipcRenderer.on('ON_NEW_NOTIFICATION', (event, message) => {
      console.log('新消息通知:' + message)
    })
    ipcRenderer.on('ON_NOTIFICATION_CLICK', (event, message) => {
      console.log('通知点击:' + message)
    })
  },
  methods: {
    sendMsg() {
      let msg = {
        title: this.title,
        content: this.content
      }
      ipcRenderer.invoke('SEND_MQ_MESSAGE', sendContent)
    }
  }
}
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue.js 是一个用于构建用户界面的 JavaScript 框架,它通常用于构建单页面应用程序(SPA)。Vue.js本身并不直接与外部消息队列(RabbitMQ)进行连接和订阅消息。但是你可以使用第三方库(例如amqp.js)来连接和订阅RabbitMQ消息。 以下是一个简单的示例,演示如何在Vue.js应用程序中使用amqp.js库连接RabbitMQ并订阅消息。 1. 首先,安装amqp.js库。可以使用npm来安装它: ``` npm install amqp-ts ``` 2. 在Vue.js应用程序的某个组件中,引入amqp.js库。例如,在Vue组件的`<script>`标签中添加以下代码: ```javascript import {Connection} from 'amqp-ts'; // 创建与RabbitMQ服务器的连接 const connection = new Connection('amqp://localhost:5672'); // 创建与指定队列的通信 const queue = connection.declareQueue('myQueueName'); // 订阅消息 queue.activateConsumer((message) => { console.log('Received message:', message.getContent()); }, {noAck: true}); ``` 这个代码片段首先创建一个与RabbitMQ服务器的连接,然后声明一个要与之通信的队列,最后使用`activateConsumer`方法订阅消息。在收到消息时,我们将使用回调函数来处理消息。 3. 如果需要在Vue组件的生命周期钩子函数中使用这些逻辑,可以将上述代码放在`created`或`mounted`钩子函数中: ```javascript export default { created() { // 上述代码放在这里 } } ``` 这样,当组件创建时或挂载时,将会连接到RabbitMQ并开始订阅消息。收到的消息将在控制台中打印出来(可以根据需求进行处理)。 请注意,此示例仅仅是一个概念示例,实际应用中需要根据具体情况进行适当的配置和错误处理。另外,为了在Vue.js应用程序中连接到RabbitMQ,需要在运行应用程序的机器上安装并运行RabbitMQ服务器。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明天你好369

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值