欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解spring集成mina实现服务端主动推送(包含心跳检测)

程序员文章站 2024-02-26 20:19:22
本文介绍了spring集成mina实现服务端主动推送(包含心跳检测),分享给大家,具体如下: 服务端 1.常规的spring工程集成mina时,pom.xml中需要...

本文介绍了spring集成mina实现服务端主动推送(包含心跳检测),分享给大家,具体如下:

服务端

1.常规的spring工程集成mina时,pom.xml中需要加入如下配置:

  <dependency>
    <groupid>org.slf4j</groupid>
    <artifactid>slf4j-jdk14</artifactid>
    <version>1.7.7</version>
  </dependency>
  <dependency>
    <groupid>org.apache.mina</groupid>
    <artifactid>mina-integration-beans</artifactid>
    <version>2.0.13</version>
  </dependency>
  <dependency>
    <groupid>org.apache.mina</groupid>
    <artifactid>mina-core</artifactid>
    <version>2.0.13</version>
    <type>bundle</type> 
    <scope>compile</scope>
  </dependency>
  <dependency>
    <groupid>org.apache.mina</groupid>
    <artifactid>mina-integration-spring</artifactid>
    <version>1.1.7</version>
  </dependency>

注意此处mina-core的配置写法。如果工程中引入上述依赖之后报错:missing artifact xxx bundle,则需要在pom.xml的plugins之间加入如下插件配置:

  <plugin>
    <groupid>org.apache.felix</groupid>
    <artifactid>maven-bundle-plugin</artifactid>
    <extensions>true</extensions>
  </plugin>

2.filter1:编解码器,实现protocolcodecfactory解码工厂

package com.he.server;
import java.nio.charset.charset;
import org.apache.mina.core.session.iosession;
import org.apache.mina.filter.codec.protocolcodecfactory;
import org.apache.mina.filter.codec.protocoldecoder;
import org.apache.mina.filter.codec.protocolencoder;
import org.apache.mina.filter.codec.textline.linedelimiter;
import org.apache.mina.filter.codec.textline.textlinedecoder;
import org.apache.mina.filter.codec.textline.textlineencoder;
public class mycodefactory implements protocolcodecfactory {
  private final textlineencoder encoder;
  private final textlinedecoder decoder;
  public mycodefactory() {
    this(charset.forname("utf-8"));
  }
  public mycodefactory(charset charset) {
    encoder = new textlineencoder(charset, linedelimiter.unix);
    decoder = new textlinedecoder(charset, linedelimiter.auto);
  }
  public protocoldecoder getdecoder(iosession arg0) throws exception {
    // todo auto-generated method stub
    return decoder;
  }
  public protocolencoder getencoder(iosession arg0) throws exception {
    // todo auto-generated method stub
    return encoder;
  }
  public int getencodermaxlinelength() {
    return encoder.getmaxlinelength();
  }
  public void setencodermaxlinelength(int maxlinelength) {
    encoder.setmaxlinelength(maxlinelength);
  }
  public int getdecodermaxlinelength() {
    return decoder.getmaxlinelength();
  }
  public void setdecodermaxlinelength(int maxlinelength) {
    decoder.setmaxlinelength(maxlinelength);
  }
}

此处使用了mina自带的textlineencoder编解码器,此解码器支持使用固定长度或者固定分隔符来区分上下两条消息。如果要使用自定义协议,则需要自己编写解码器。要使用websocket,也需要重新编写解码器,关于mina结合websocket,jira上有一个开源项目https://issues.apache.org/jira/browse/dirmina-907,专门为mina编写了支持websocket的编解码器,亲测可用。。。此部分不是本文重点,略。

3.filter2:心跳工厂,加入心跳检测功能需要实现keepalivemessagefactory:

package com.he.server;
import org.apache.log4j.logger;
import org.apache.mina.core.session.iosession;
import org.apache.mina.filter.keepalive.keepalivemessagefactory;
public class mykeepalivemessagefactory implements keepalivemessagefactory{

  private final logger log = logger.getlogger(mykeepalivemessagefactory.class);

  /** 心跳包内容 */ 
  private static final string heartbeatrequest = "1111"; 
  private static final string heartbeatresponse = "1112"; 
  public object getrequest(iosession session) {
    log.warn("请求预设信息: " + heartbeatrequest); 
     return heartbeatrequest;
  }
  public object getresponse(iosession session, object request) {
    log.warn("响应预设信息: " + heartbeatresponse); 
    /** 返回预设语句 */ 
    return heartbeatresponse; 
  }
  public boolean isrequest(iosession session, object message) {
     log.warn("请求心跳包信息: " + message); 
     if (message.equals(heartbeatrequest)) 
       return true; 
     return false; 
  }
  public boolean isresponse(iosession session, object message) {
   log.warn("响应心跳包信息: " + message); 
   if(message.equals(heartbeatresponse)) 
     return true;
    return false;
  }
}

此处我设置服务端发送的心跳包是1111,客户端应该返回1112.

4.实现必不可少的iohandleradapter,得到监听事件处理权:

package com.he.server;
import java.net.inetsocketaddress;
import java.util.collections;
import java.util.hashset;
import java.util.set;
import java.util.concurrent.concurrenthashmap;
import org.apache.log4j.logger;
import org.apache.mina.core.service.iohandleradapter;
import org.apache.mina.core.session.idlestatus;
import org.apache.mina.core.session.iosession;
public class myhandler extends iohandleradapter {
  //private final int idle = 3000;//(单位s)
  private final logger log = logger.getlogger(myhandler.class);
  // public static set<iosession> sessions = collections.synchronizedset(new hashset<iosession>());
  public static concurrenthashmap<long, iosession> sessionsconcurrenthashmap = new concurrenthashmap<long, iosession>();
  @override
  public void exceptioncaught(iosession session, throwable cause) throws exception {
    session.closeonflush();
    log.warn("session occured exception, so close it." + cause.getmessage());
  }
  @override
  public void messagereceived(iosession session, object message) throws exception {
    string str = message.tostring();
    log.warn("客户端" + ((inetsocketaddress) session.getremoteaddress()).getaddress().gethostaddress() + "连接成功!");
    session.setattribute("type", message);
    string remoteaddress = ((inetsocketaddress) session.getremoteaddress()).getaddress().gethostaddress();
    session.setattribute("ip", remoteaddress);
    log.warn("服务器收到的消息是:" + str);
    session.write("welcome by he");
  }
  @override
  public void messagesent(iosession session, object message) throws exception {
    log.warn("messagesent:" + message);
  }
  @override
  public void sessioncreated(iosession session) throws exception {
    log.warn("remote client [" + session.getremoteaddress().tostring() + "] connected.");
    // my
    long time = system.currenttimemillis();
    session.setattribute("id", time);
    sessionsconcurrenthashmap.put(time, session);
  }
  @override
  public void sessionclosed(iosession session) throws exception {
    log.warn("sessionclosed.");
    session.closeonflush();
    // my
    sessionsconcurrenthashmap.remove(session.getattribute("id"));
  }
  @override
  public void sessionidle(iosession session, idlestatus status) throws exception {
    log.warn("session idle, so disconnecting......");
    session.closeonflush();
    log.warn("disconnected.");
  }
  @override
  public void sessionopened(iosession session) throws exception {
    log.warn("sessionopened.");
    // 
    //session.getconfig().setidletime(idlestatus.both_idle, idle);
  }
}

此处有几点说明:

第一点:网上教程会在此处(sessionopened()方法中)设置idle,idle表示session经过多久判定为空闲的时间,单位s,上述代码中已经注释掉了,因为后面在spring配置中加入心跳检测部分时会进行idle的配置,已经不需要在此处进行配置了,而且如果在心跳配置部分和此处都对both_idle模式设置了空闲时间,亲测发现此处配置不生效。

第二点:关于存放session的容器,建议使用

复制代码 代码如下:

public static concurrenthashmap<long, iosession> sessionsconcurrenthashmap = new concurrenthashmap<long, iosession>();

而不是用已经注释掉的collections.synchronizedset类型的set或者map,至于原因,java5中新增了concurrentmap接口和它的一个实现类concurrenthashmap,可以保证线程的足够安全。详细的知识你应该搜索synchronizedmap和concurrenthashmap的区别,学习更加多的并发安全知识。

上述代码中,每次在收到客户端的消息时,我会返回一段文本:welcome by he。

有了map,主动推送就不是问题了,想推给谁,在map中找到谁就可以了。

5.完成spring的配置工作

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  <bean class="org.springframework.beans.factory.config.customeditorconfigurer">
    <property name="customeditors">
      <map>
        <entry key="java.net.socketaddress"
          value="org.apache.mina.integration.beans.inetsocketaddresseditor">
        </entry>
      </map>
    </property>
  </bean>
  <bean id="ioacceptor" class="org.apache.mina.transport.socket.nio.niosocketacceptor"
    init-method="bind" destroy-method="unbind">
    <!--端口号-->
    <property name="defaultlocaladdress" value=":8888" />
    <!--绑定自己实现的handler-->
    <property name="handler" ref="serverhandler" />
    <!--声明过滤器的集合-->
    <property name="filterchainbuilder" ref="filterchainbuilder" />
    <property name="reuseaddress" value="true" />
  </bean>

  <bean id="filterchainbuilder"
    class="org.apache.mina.core.filterchain.defaultiofilterchainbuilder">
    <property name="filters">
      <map>
        <!--mina自带的线程池filter-->
        <entry key="executor" value-ref="executorfilter" />
        <entry key="mdcinjectionfilter" value-ref="mdcinjectionfilter" />
        <!--自己实现的编解码器filter-->
        <entry key="codecfilter" value-ref="codecfilter" />
        <!--日志的filter-->
        <entry key="loggingfilter" value-ref="loggingfilter" />
        <!--心跳filter-->
        <entry key="keepalivefilter" value-ref="keepalivefilter" />
      </map>
    </property>
  </bean>
 <!-- executorfilter多线程处理 --> 
  <bean id="executorfilter" class="org.apache.mina.filter.executor.executorfilter" />
  <bean id="mdcinjectionfilter" class="org.apache.mina.filter.logging.mdcinjectionfilter">
    <constructor-arg value="remoteaddress" />
  </bean>

  <!--日志-->
  <bean id="loggingfilter" class="org.apache.mina.filter.logging.loggingfilter" />

  <!--编解码-->
  <bean id="codecfilter" class="org.apache.mina.filter.codec.protocolcodecfilter">
    <constructor-arg>
      <!--构造函数的参数传入自己实现的对象-->
      <bean class="com.he.server.mycodefactory"></bean>
    </constructor-arg>
  </bean>

  <!--心跳检测filter-->
  <bean id="keepalivefilter" class="org.apache.mina.filter.keepalive.keepalivefilter">
    <!--构造函数的第一个参数传入自己实现的工厂-->
    <constructor-arg>
      <bean class="com.he.server.mykeepalivemessagefactory"></bean>
    </constructor-arg>
    <!--第二个参数需要的是idlestatus对象,value值设置为读写空闲-->
    <constructor-arg type = "org.apache.mina.core.session.idlestatus" value="both_idle" >
    </constructor-arg>
    <!--心跳频率,不设置则默认60s -->
    <property name="requestinterval" value="5" />
    <!--心跳超时时间,不设置则默认30s  -->
    <property name="requesttimeout" value="10" />
    <!--不设置默认false-->
    <property name="forwardevent" value="true" />
  </bean>

  <!--自己实现的handler-->
  <bean id="serverhandler" class="com.he.server.myhandler" />
</beans>

好了,xml中已经写了足够多的注释了。说明一下关于心跳检测中的最后一个属性:forwardevent,默认false,比如在心跳频率为5s时,实际上每5s会触发一次keepalivefilter中的session_idle事件,该事件中开始发送心跳包。当此参数设置为false时,对于session_idle事件不再传递给其他filter,如果设置为true,则会传递给其他filter,例如handler中的session_idle事件,此时也会被触发。另外idlestatus一共有三个值,点击进源码就能看到。

6.写main方法启动服务端

package com.he.server;
import org.springframework.context.applicationcontext;
import org.springframework.context.support.classpathxmlapplicationcontext;
public class maintest {
  public static void main(string[] args) {
    classpathxmlapplicationcontext ct = new classpathxmlapplicationcontext("applicationcontext.xml");
  }
}

run之后,端口就已经开始监听了。此处,如果是web工程,使用tomcat之类的容器,只要在web.xml中配置了

  <context-param>
    <param-name>contextconfiglocation</param-name>
    <param-value>/web-inf/classes/applicationcontext.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.contextloaderlistener</listener-class>
  </listener>

则容器在启动时就会加载spring的配置文件,端口的监听就开始了,这样就不需要main方法来启动。

客户端,本文采用两种方式来实现客户端

方式一:用mina结构来实现客户端,引入mina相关jar包即可,android也可以使用

1.先实现iohandleradater得到监听事件,类似于服务端:

package com.he.client.minaclient;
import org.apache.log4j.logger;
import org.apache.mina.core.service.iohandleradapter;
import org.apache.mina.core.session.idlestatus;
import org.apache.mina.core.session.iosession;
public class clienthandler extends iohandleradapter{
  private final logger log = logger.getlogger(clienthandler.class); 

  @override
  public void messagereceived(iosession session, object message) throws exception {
    // todo auto-generated method stub
    log.warn("客户端收到消息:" + message);
    if (message.tostring().equals("1111")) {
      //收到心跳包
      log.warn("收到心跳包");
      session.write("1112");
    }
  }

  @override
  public void messagesent(iosession session, object message) throws exception {
    // todo auto-generated method stub
    super.messagesent(session, message);
  }

  @override
  public void sessionclosed(iosession session) throws exception {
    // todo auto-generated method stub
    super.sessionclosed(session);
  }

  @override
  public void sessioncreated(iosession session) throws exception {
    // todo auto-generated method stub
    super.sessioncreated(session);
  }

  @override
  public void sessionidle(iosession session, idlestatus status) throws exception {
    // todo auto-generated method stub
    super.sessionidle(session, status);
  }

  @override
  public void sessionopened(iosession session) throws exception {
    // todo auto-generated method stub
    super.sessionopened(session);
  }
}

2.写main方法启动客户端,连接服务端:

package com.he.client.minaclient;
import java.net.inetsocketaddress;
import java.nio.charset.charset;
import org.apache.mina.core.future.connectfuture;
import org.apache.mina.filter.codec.protocolcodecfilter;
import org.apache.mina.filter.codec.textline.textlinecodecfactory;
import org.apache.mina.filter.logging.loggingfilter;
import org.apache.mina.transport.socket.nio.niosocketconnector;
public class clienttest {
  public static void main(string[] args) throws interruptedexception {
    //创建客户端连接器. 
    niosocketconnector connector = new niosocketconnector();
    connector.getfilterchain().addlast("logger", new loggingfilter());
    connector.getfilterchain().addlast("codec",
        new protocolcodecfilter(new textlinecodecfactory(charset.forname("utf-8")))); //设置编码过滤器 
    connector.sethandler(new clienthandler());//设置事件处理器 
    connectfuture cf = connector.connect(new inetsocketaddress("127.0.0.1", 8888));//建立连接 
    cf.awaituninterruptibly();//等待连接创建完成 
    cf.getsession().write("hello,测试!");//发送消息,中英文都有 
    //cf.getsession().closeonflush();
    //cf.getsession().getclosefuture().awaituninterruptibly();//等待连接断开 
    //connector.dispose();
  }
}

过程也是一样的,加各种filter,绑定handler。上述代码运行之后向服务器发送了:“hello,测试”,并且收到返回值:welcome by he。然后每隔5s,就会收到服务端的心跳包:1111。在handler的messagereceived中,确认收到心跳包之后返回1112,实现心跳应答。以上过程,每5s重复一次。

main方法中最后三行注释掉的代码如果打开,客户端在发送完消息之后会主动断开。

方式二:客户端不借助于mina,换用java的普通socket来实现,这样就可以换成其他任何语言:

package com.he.client;
import java.io.datainputstream;
import java.io.ioexception;
import java.io.printwriter;
import java.net.socket;
/**
 *@function:java的简单socket连接,长连接,尝试连续从服务器获取消息
 *@parameter:
 *@return:
 *@date:2016-6-22 下午03:43:18
 *@author:he
 *@notice:
 */
public class sockettesttwo {
  public static final string ip_addr = "127.0.0.1";// 服务器地址
  public static final int port = 8888;// 服务器端口号
  static string text = null;
  public static void main(string[] args) throws ioexception {
    system.out.println("客户端启动...");
    socket socket = null;
    socket = new socket(ip_addr, port);
    printwriter os = new printwriter(socket.getoutputstream());
    os.println("al");
    os.println("two");
    os.flush();
    while (true) {
      try {
        // 创建一个流套接字并将其连接到指定主机上的指定端口号
        datainputstream input = new datainputstream(socket.getinputstream());
        // 读取服务器端数据
        byte[] buffer;
        buffer = new byte[input.available()];
        if (buffer.length != 0) {
          system.out.println("length=" + buffer.length);
          // 读取缓冲区
          input.read(buffer);
          // 转换字符串
          string three = new string(buffer);
          system.out.println("内容=" + three);
          if (three.equals("1111\n")) {
            system.out.println("发送返回心跳包");
            os = new printwriter(socket.getoutputstream());
            os.println("1112");
            os.flush();
          }
        }
      } catch (exception e) {
        system.out.println("客户端异常:" + e.getmessage());
        os.close();
      }
    }
  }
}

以上代码运行效果和前一种方式完全一样。

但是注意此种方法和使用mina结构的客户端中有一处不同:对于心跳包的判断。本教程中服务端选用了mina自带的编解码器,通过换行符来区分上下两条消息,也就是每一条消息后面会带上一个换行符,所以在使用java普通的socket来连接时,判断心跳包不再是判断是否为“1111”,而是“1111\n”。对比mina结构的客户端中并不需要加上换行符是因为客户端中绑定了相同的编解码器。

程序运行结果截图:

服务端:

详解spring集成mina实现服务端主动推送(包含心跳检测) 

客户端:

详解spring集成mina实现服务端主动推送(包含心跳检测)

红色的打印是mina自带的打印信息,黑色的是本工程中使用的log4j打印,所以你们的工程应该配置有如下log4j的配置文件才能看到一样的打印结果:

log4j.rootlogger=warn,stdout

log4j.appender.stdout = org.apache.log4j.consoleappender
log4j.appender.stdout.layout = org.apache.log4j.patternlayout
log4j.appender.stdout.threshold=warn
log4j.appender.stdout.layout.conversionpattern = [%-5p] [%d{yyyy-mm-dd hh\:mm\:ss,sss}] [%x] %c %l - %m%n 

应大家需求,工程代码终于抽空放到github了! https://github.com/smile326/minaspring

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。