首页 > 其他分享 >使用ActiveMQ Artemis进行重连

使用ActiveMQ Artemis进行重连

时间:2023-01-15 10:00:12浏览次数:30  
标签:function val send Artemis connect 重连 ActiveMQ 连接

正常创建一个连接,在一段时间后心跳就会因为接收不到数据而强制停止。从而断开连接,那么无论是前端还是后端都应该有自己的实现重连机制。这里写一个关于前端实现重连的机制:

代码如下:

点击查看代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Chat Example Using STOMP Over WebSockets</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap.min.responsive.css" rel="stylesheet">
    <style type="text/css">
      body { padding-top: 40px; }
    </style>
  </head>

  <body>
    
    <div class="navbar navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container">
          <a class="brand" href="#">Stomp Over WebSocket Chat Example</a>
        </div>
      </div>
    </div>

    <div class="container-fluid">
      <div class="row-fluid">
        <div class="span6">
          <div id="connect">
            <div class="page-header">
              <h2>Server Login</h2>
            </div>
            <form class="form-horizontal" id='connect_form'>
              <fieldset>
                <div class="control-group" style="display:none">
                  <label>WebSocket URL</label>
                  <div class="controls">
                    <input name=url id='connect_url' value='ws://127.0.0.1:61613' type="text">
                  </div>
                </div>
                <div class="control-group" style="display:none">
                  <label>User</label>
                  <div class="controls">
                    <input id='connect_login' placeholder="User Login" value="admin" type="text">
                  </div>
                </div>
                <div class="control-group">
                  <label>ID</label>
                  <div class="controls">
                    <input id='connect_id' placeholder="ID" value="" type="text">
                  </div>
                </div>
                <div class="control-group">
                  <label>Password</label>
                  <div class="controls">
                    <input id='connect_passcode' placeholder="User Password" value="password" type="password">
                  </div>
                </div>
                <div class="control-group">
                  <label>Destination</label>
                  <div class="controls">
                    <input id='destination' placeholder="Destination" value="world" type="text">
                  </div>
                </div>
                <div class="form-actions">
                  <button id='connect_submit' type="submit" class="btn btn-large btn-primary">Connect</button>
                </div>
              </fieldset>
            </form>
          </div>
          <div id="connected" style="display:none">
            <div class="page-header">
              <h2>Chat Room</h2>
            </div>
            <div id="messages">
            </div>
            <form class="well form-search" id='send_form'>
              <button class="btn" type="button" id='disconnect' style="float:right">Disconnect</button>
              <input class="input-medium" id='send_form_input' placeholder="Type your message here" class="span6"/>
              <button class="btn" type="submit">Send</button>
            </form>
          </div>
        </div>
        <div class="span4">
          <div class="page-header">
            <h2>Debug Log</h2>
          </div>
          <pre id="debug"></pre>
        </div>
      </div>
    </div>

    <!-- Scripts placed at the end of the document so the pages load faster -->
    <script src='js/jquery-1.7.2.min.js'></script>
    <script src="js/stomp2.3.3.js"></script>
    <script>//<![CDATA[
	//定义全局变量,表明一个session
	var client = null;
	const data = new Map();
	function connect(){    //定义链接函数
		if(client == null || !client.connected){    
			//var url = 'http://localhost:8164/websocket';
			//var url = '/websocket';
			var headers={
				'login':data.get('login'),
				'passcode':data.get('passcode'),
				'client-id': data.get('id')
			};
			client = Stomp.client(data.get('url'));
			client.connect(headers, connectCallback ,errorCallback );
		}else{
			$("#debug").append("当前处于链接状态" + "\n");
		}
	}

	function connectCallback (frame) {  //链接成功时的回调函数
		client.subscribe('world', function (result) {  
			var content = result.body;
			$("#messages").append('<p>'+content+'</p>' + "\n");
		}, {});       
	}
	function errorCallback(){//链接失败时的回调函数,此函数从新调用链接方法,造成循环,直到链接成功    
		connect();   
		var d = new Date();
		console.log(d.getDate()+d.getHours()+d.getMinutes()+"执行了重连。。。"); 
	}

    $(document).ready(function() {
      if(window.WebSocket) {
        $('#connect_form').submit(function() {
        	data.set('url',$("#connect_url").val());
        	data.set('login',$("#connect_login").val());
        	data.set('passcode',$("#connect_passcode").val());
        	data.set('id',$("#connect_id").val());
        	connect();//创建链接
        	 $('#connect').remove();
        	 $('#connected').css('display','');
          // this allows to display debug logs directly on the web page
          //client.debug = function(str) {
            //$("#messages").append("<p>" +str.body+ "</p>" +"\n");
            //$("#debug").append(str + "\n");
         // };
          return false;
        });
  
        $('#disconnect').click(function() {
          client.disconnect(function() {
            $('#connected').fadeOut({ duration: 'fast' });
            $('#connect').fadeIn();
            $("#messages").html("")
          });
          location.reload ();
          return false;
        });
   
        $('#send_form').submit(function() {
          var text = $('#send_form_input').val();
          if (text) {
            client.send('world', {}, text);
            $('#send_form_input').val("");
          }
          return false;
        });
      } else {
        $("#connect").html("\
            <h1>Get a new Web Browser!</h1>\
            <p>\
            Your browser does not support WebSockets. This example will not work properly.<br>\
            Please use a Web Browser with WebSockets support (WebKit or Google Chrome).\
            </p>\
        ");
      }
    });
    //]]></script>

  </body>
</html>

实现原理很简单,使用stomp进行连接,里面定义了连接方法client.connect(headers, connectCallback ,errorCallback );分别是头信息,连接成功回调,和连接失败回调,
底层实现的是windows.setinterval()方法进行定时检测连接是否正常。这样服务启动后就会一直有正常的连接支持。遗憾的是这种连接方法并不能使同一个sessionid的连接重连。而是取到我们填写的信息再次连接。

标签:function,val,send,Artemis,connect,重连,ActiveMQ,连接
From: https://www.cnblogs.com/jingwei129/p/17053110.html

相关文章

  • ActiveMQ和spring集成
    1.消息发送类packagecn.com.biceng.jms.queue;importjavax.jms.Destination;importjavax.jms.JMSException;importjavax.jms.Message;importjavax.jms.Session;import......
  • docker运行不同版本activemq相关问题
    WARNING:Therequestedimage'splatform(linux/amd64)doesnotmatchthedetectedhostplatform(linux/arm64/v8)andnospecificplatformwasrequestedda6992c......
  • ActiveMQ
    ActiveMQ初体验首先介绍下MQ,MQ英文名MessageQueue,中文名也就是大家用的消息队列,干嘛用的呢,说白了就是一个消息的接受和转发的容器,可用于消息推送。下面介绍主题,就是今天为大......
  • SpringBoot2.x系列教程60--SpringBoot整合消息队列之ActiveMQ环境配置
    SpringBoot2.x系列教程60--SpringBoot整合消息队列之ActiveMQ环境配置作者:一一哥我在上一章节中,给大家介绍了JMS协议及消息中间件,消息队列等概念,本节中我会介绍ActiveMQ的概......
  • SpringBoot2.x系列教程61--SpringBoot整合消息队列之ActiveMQ代码实现异步消息传递及
    SpringBoot2.x系列教程61--SpringBoot整合消息队列之ActiveMQ代码实现消息传递作者:一一哥我在上一章节中,给大家介绍了ActiveMQ,本节中我会介绍SpringBoot中如何整合ActiveMQ......
  • golang实现tcp自动重连示例程序
    参考代码:packagemainimport("fmt""net""time")funcdoTask(){time.Sleep(1*time.Second)main()}funcmain(){for{conn,err......
  • 七、activemq整合springmvc之queue
    一、前言spring代码基于​​SSM整合(spring-springmvc-mybatis)之CRUD ​​;代码地址:(基础版本:​​https://gitee.com/joy521125/ssm-senior-base.git​​​maven版:​​htt......
  • 校园网断线重连,用爬虫来搞定!
    前言hello,大家好,我是大赛哥(弟),好久不见,甚是想念。最近因为有小需求研究了两登录的加密,也成功解密加密的参数,在这里给大家分享一波。前段时间,有个同学他实验室服务器校园网......
  • 播放器重连机制
    在实际业务中,偶尔会碰到网络波动导致播放链接断开的情况,这时候播放器就需要加入一个重连机制,让播放器自动重连,在网络恢复之后,可以及时的重连回去。1.首先监听播放器播放停......
  • ActiveMQ架构设计与最佳实践
    ActiveMQ是最常用、特性最丰富的消息中间件,通常用于消息异步通信、调用解耦等多种场景,是JMS规范的实现者之一。 一、架构设计概要  ActiveMQ提供两种可供实施的架构模......