Apache mina 与Spring整合设计
其实很简单,看了网上很多例子,但是发现还是Apache自己写的比较好,于是就抄下来了。
先说配置文件,注意这里不能使用延迟加载和“byName”的方式找bean
<?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-2.5.xsd" default-lazy-init="false"><!--This makes it possible to specify java.net.SocketAddress values (e.g.:80 below) as Strings. They will be converted intojava.net.InetSocketAddress objects by Spring.--><bean /></entry></map></property></bean><!-- The IoHandler implementation --><bean id="myHandler" /></list></property></bean><!--By default MINA uses an ExecutorThreadModel. This demonstrates how touse your own with some non default settings. The threadModel will beset on the SocketAcceptorConfig defined below. To configure aExecutorFilter directly you will have to use the ThreadModel.MANUALThreadModel instead.--><bean id="threadModel"value="MyMinaService" /><property name="executor"><beanvalue="2" /><property name="maxPoolSize" value="30" /><property name="keepAliveSeconds" value="30" /></bean></property></bean><bean id="ioAcceptor"/></property><property name="bindings"><list><bean value=":8081" /><property name="handler" ref="myHandler" /><property name="serviceConfig"><bean ref="filterChainBuilder" /><property name="reuseAddress" value="true" /><property name="threadModel" ref="threadModel" /></bean></property></bean></list></property></bean></beans>
public class MyProtocolHandler extends IoHandlerAdapter {@Overridepublic void messageReceived(IoSession session, Object message) throws Exception {if (message instanceof ByteBuffer) {ByteBuffer rb = (ByteBuffer) message;byte[] moMessage = new byte[rb.remaining()];rb.get(moMessage);Endpoint endpoint = new MinaEndpoint(session);endpoint.receive(moMessage);}super.messageReceived(session, message);}}
public class MinaEndpoint implements Endpoint {private IoSession session;public MinaEndpoint(IoSession session) {this.session = session;}public void send(byte[] data) {if (session.isConnected() && ArrayUtils.isEmpty(data)) {ByteBuffer byteBuffer = ByteBuffer.allocate(data.length); byteBuffer.put(data);byteBuffer.flip();session.write(byteBuffer);}}public void receive(byte[] data) {//Service的实现操作}