mina2.0 spring

时间:2022-07-02 13:04:39

Apache MINA是一个网络应用程序框架,它可以帮助用户开发的高性能、高扩展性的网络应用程序。它提供了一个抽象的事件驱动的异步API在不同传输如TCP/IP和UDP/IP通过java NIO。

Apache MINA通常被称为:

NIO框架库,
客户端服务器框架库,或
一个网络socket库

code案例:

test.properties 配置文件

 #mina2.0
mina.server.serverLocationAddress = 127.0.0.1:9998

applicationContext.xml 配置文件

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:propertiesConfig/test.properties</value>
</property>
</bean>
<!-- 定义数据处理Bean -->
<bean id="serverHandler" class="com.maven.project.web.mina2.ServerHandler" /> <!-- 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="codecFilter" class="org.apache.mina.filter.codec.ProtocolCodecFilter">
<constructor-arg>
<!-- <bean class="org.apache.mina.filter.codec.textline.TextLineCodecFactory" />-->
<!-- 处理对象流时候用ObjectSerializationCodecFactory -->
<!-- <bean class="org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory" /> -->
<bean class="com.maven.project.web.mina2.ServerCodeFactory" />
</constructor-arg>
</bean> <!-- 日志过滤器 -->
<bean id="loggingFilter" class="org.apache.mina.filter.logging.LoggingFilter" /> <!-- 过滤器链 -->
<bean id="filterChainBuilder" class="org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder">
<property name="filters">
<map>
<entry key="executor" value-ref="executorFilter" />
<entry key="mdcInjectionFilter" value-ref="mdcInjectionFilter" />
<entry key="codecFilter" value-ref="codecFilter" />
<entry key="loggingFilter" value-ref="loggingFilter" />
</map>
</property>
</bean> <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.net.SocketAddress" value="org.apache.mina.integration.beans.InetSocketAddressEditor"/>
</map>
</property>
</bean> <!-- session config 通过工厂方法注入 -->
<bean id="sessionConfig" factory-bean="ioAcceptor" factory-method="getSessionConfig" >
<property name="bothIdleTime" value="180"/><!-- 配置session 空闲时间,单位 秒 -->
</bean> <bean id="ioAcceptor" class="org.apache.mina.transport.socket.nio.NioSocketAcceptor" init-method="bind" destroy-method="unbind">
<property name="defaultLocalAddress" value="${mina.server.serverLocationAddress}" />
<property name="handler" ref="serverHandler" />
<property name="filterChainBuilder" ref="filterChainBuilder" />
<property name="reuseAddress" value="true" />
</bean>
</beans>

maven pom.xml 配置文件

     <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<mina-version>2.0.13</mina-version>
<mina-groupId>org.apache.mina</mina-groupId>
</properties>
<!-- mina -->
<dependency>
<groupId>${mina-groupId}</groupId>
<artifactId>mina-core</artifactId>
<version>${mina-version}</version>
</dependency>
<dependency>
<groupId>${mina-groupId}</groupId>
<artifactId>mina-integration-beans</artifactId>
<version>${mina-version}</version>
</dependency>

handler 业务处理类

 package com.maven.project.web.mina2;

 import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession; public class ServerHandler extends IoHandlerAdapter { /**当一个新客户端连接后触发此方法*/
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("===============sessionCreated=============");
} /**当连接后打开时触发此方法,一般此方法与 sessionCreated 会被同时触发*/
@Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("===============sessionOpened=============");
} /**当连接被关闭时触发,例如客户端程序意外退出等等*/
@Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("===============sessionClosed=============");
if(null != session){
session.closeOnFlush();
}
} /**当连接空闲时触发此方法*/
@Override
public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
System.out.println("===============sessionIdle=============");
this.sessionClosed(session);
} /**当接口中其他方法抛出异常未被捕获时触发此方法*/
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
System.out.println("===============exceptionCaught=============");
this.sessionClosed(session);
} /**当接收到客户端的请求信息后触发此方法*/
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
System.out.println("===============messageReceived============="+message);
} /**当信息已经传送给客户端后触发此方法*/
@Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("===============messageSent=============");
} @Override
public void inputClosed(IoSession session) throws Exception {
System.out.println("===============inputClosed=============");
this.sessionClosed(session);
} }

encode 类

 package com.maven.project.web.mina2;

 import java.nio.charset.Charset;

 import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoder;
import org.apache.mina.filter.codec.ProtocolEncoderOutput; public class ServerEnCoder implements ProtocolEncoder { private Charset charset = null; public ServerEnCoder(Charset charset) {
this.charset = charset;
} @Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
IoBuffer buf = IoBuffer.allocate(message.toString().getBytes().length).setAutoExpand(true);
buf.putString(message.toString(), charset.newEncoder());
buf.flip();
out.write(buf);
return;
} @Override
public void dispose(IoSession session) throws Exception { } }

decode 类

 package com.maven.project.web.mina2;

 import java.nio.charset.Charset;

 import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput; public class ServerDecoder extends CumulativeProtocolDecoder { private static final int HANDLENGTH = 4; private Charset charset = null; public ServerDecoder(Charset charset) {
this.charset = charset;
} @Override
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
if (in.remaining() < HANDLENGTH) {
return false;
}
byte[] sizeBytes = new byte[HANDLENGTH];
in.mark();// 标记当前位置,以便reset
in.get(sizeBytes, 0, HANDLENGTH);// 读取4字节
int size = Integer.parseInt(new String(sizeBytes, this.charset));
in.reset();
if (size > in.remaining()) {// 如果消息内容不够,则重置,相当于不读取size
return false;// 父类接收新数据,以拼凑成完整数据
} else {
byte[] bytes = new byte[size];
in.get(bytes, 0, size);
out.write(new String(bytes, this.charset));
if (in.remaining() > 0) {// 如果读取内容后还粘了包,就让父类再重读 一次,进行下一次解析
return true;
}
}
return false;// 处理成功,让父类进行接收下个包
}
}

编码过滤工厂

 package com.maven.project.web.mina2;

 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; public class ServerCodeFactory implements ProtocolCodecFactory { private ServerEnCoder encoder; private ServerDecoder decoder; public ServerCodeFactory(){
this(Charset.defaultCharset().name());
} public ServerCodeFactory(String charsetName){
encoder = new ServerEnCoder(Charset.forName(charsetName));
decoder = new ServerDecoder(Charset.forName(charsetName));
} @Override
public ProtocolEncoder getEncoder(IoSession session) throws Exception {
return encoder;
} @Override
public ProtocolDecoder getDecoder(IoSession session) throws Exception {
return decoder;
} }