1.package.json中
"dependencies": {
...
"vertx3-eventbus-client": "3.5.2",
},
然后 npm install
叔营,或者:
npm install vertx3-eventbus-client@3.5.2
2.angular-cli.json中
"scripts": [
...
"../node_modules/vertx3-eventbus-client/vertx-eventbus.js"
],
3.創(chuàng)建一個(gè)eventbus.service.ts用來通信
導(dǎo)入eventbus:
import { EventBus } from 'vertx3-eventbus-client';
聲明eventbus:
declare var EventBus: any;
4.創(chuàng)建eventbus實(shí)例,監(jiān)聽接口以及發(fā)送消息
//創(chuàng)建實(shí)例
var eb = new EventBus('http://localhost:8080/eventbus');
eb.onopen = function() {
//注冊(cè)監(jiān)聽器用來接受消息
eb.registerHandler('some-address', function(error, message) {
console.log('received a message: ' + JSON.stringify(message));
});
//發(fā)送消息
eb.send('some-address', {name: 'tim', age: 587});
}
更多信息請(qǐng)參考這里 https://vertx.io/docs/vertx-web/java/
注:
對(duì)于需要發(fā)送消息來接受的消息,需要先監(jiān)聽筒主,然后再發(fā)送消息阵谚。
對(duì)于一直推送的消息黑忱,不需要發(fā)送。
代碼實(shí)例如下:
RegisterHandler(key, id, callback) {
const address = '***.' + key + '.' + id;
if (typeof (this.eventBus[key]) === 'undefined' || !this.eventBus[key]) {
this.eventBus[key] = new EventBus(environment.eventbusUrl);
}
if (this.eventBus[key].state === EventBus.OPEN) {
this.eventBus[key].registerHandler(address, callback);
} else {
const $this = this;
this.eventBus[key].onopen = function () {
$this.eventBus[key].registerHandler(address, callback)
}
}
}
Send(key, id) {
var data = '';
const address = ***.' + key + '.' + id;
if (typeof (this.eventBus[key]) === 'undefined' || !this.eventBus[key]) {
this.eventBus[key] = new EventBus(environment.eventbusUrl);
}
if (this.eventBus[key].state === EventBus.OPEN) {
this.eventBus[key].send(address, data)
} else {
const $this = this;
this.eventBus[key].onopen = function () {
$this.eventBus[key].send(address, data)
}
}
}
closeEventBus(key) {
if (typeof (this.eventBus[key]) !== 'undefined' && this.eventBus[key] && this.eventBus[key].state === EventBus.OPEN) {
this.eventBus[key].close();
}
this.eventBus[key] = null;
}
在組件ngOnDestroy中調(diào)用closeEventBus關(guān)閉eventbus袄膏。