首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 服务器 > Apache >

Apache mina 与Spring调整设计

2012-10-26 
Apache mina 与Spring整合设计其实很简单,看了网上很多例子,但是发现还是Apache自己写的比较好,于是就抄下

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>


再然后我们只需要实现MyProtocolHandler就可以了,只在接收数据加了处理,数据传输用的是byte[],MinaEndpoint里面来执行自己的代码就行了
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);}}

最后就是EndPoint了,其实就两个方法,一个接收,一个发送
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的实现操作}

其实这玩意主要还是配置文件,这个还是抄自IoAcceptorFactoryBean的API的说明,呵呵

热点排行