spring整合mina簡明教程

Mr孔先森發表於2015-08-20
mina服務端程式碼如下:
try {
            IoAcceptor accept = new NioSocketAcceptor();
            DefaultIoFilterChainBuilder chain = accept.getFilterChain();
            accept.getSessionConfig().setReadBufferSize(2048);
            accept.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,10);
            accept.setHandler(new ServerHandler());
            LoggingFilter loggingFilter = new LoggingFilter();
            chain.addLast("logging", loggingFilter);
            chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(
                    Charset.forName("UTF-8"),LineDelimiter.WINDOWS.getValue(),
                    LineDelimiter.WINDOWS.getValue())));
            accept.bind(new InetSocketAddress(9123));
            logger.info("server成功啟動");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

ServerHandler的程式碼如下:
public class ServerHandler extends IoHandlerAdapter{
    private static final Logger log = Logger.getLogger(ServerHandler.class);
    @Override
    public void sessionCreated(IoSession session) throws Exception {
        InetSocketAddress adress = (InetSocketAddress) session.getRemoteAddress();
        System.out.println("hostString:"+adress.getHostString());
        System.out.println("hostName:"+adress.getHostName());
        System.out.println("address:"+adress.getAddress());
        System.out.println("port:"+adress.getPort());
       
    }
    @Override
    public void messageReceived(IoSession session,Object message)throws Exception{
        String str = message.toString();
        log.info("The message received is ["+str+"]");
        
        System.out.println("the message received is "+str);
        if(str.endsWith("quit")){
            session.close(true);
            return;
        }
    }
}  

在spring中整合mina無非是將建立物件和給物件設定屬性的過程以配置檔案的形式實現
配置檔案如下:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
    <bean id="serverHandler" class="com.snail.mina.server.ServerHandler"/>
    <bean id="protocolCodecFilter" class="org.apache.mina.filter.codec.ProtocolCodecFilter">
        <constructor-arg>
            <bean class="org.apache.mina.filter.codec.textline.TextLineCodecFactory"/>
            
        </constructor-arg>
    </bean>
    <bean id="defaultIoFilterChainBuilder" class="org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder">
        <property name="filters">
            <map>
                <entry key="codecFilter" value-ref="protocolCodecFilter"/>
            </map>
        </property>
    </bean>
    <bean id="ioAcceptor" class="org.apache.mina.transport.socket.nio.NioSocketAcceptor"
        init-method="bind" destroy-method="unbind">
        <span style="color:#FF0000;"><property name="defaultLocalAddress" value=":9123"/>①//問題所在</span>
        <property name="handler" ref="serverHandler"/>
        <property name="filterChainBuilder" ref="defaultIoFilterChainBuilder"/>
    
    </bean>
</beans>  
問題就出在①處,該處對應的java程式碼如下:
accept.bind(new InetSocketAddress(9123));
這句話的意思是給IoAccept繫結監聽埠,我們知道spring中的value都是字串,雖然value可以自動轉化成int,double等型別,但是value不能轉化成物件,那我們如何解決呢?
===================================================================
解決辦法:
spring中的屬性編輯器可以幫我們解決這個問題,當我們想用字串來表示物件時我們就需要用到屬性編輯器,對於本例中需要用到的引數InetSocketAddress來說,spring中自帶了該型別的編輯器,配置如下(如需其他屬性編輯器請自行搜尋):
    <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
        <property name="customEditors">
            <map>
                <entry key="java.net.SocketAddress">
                    <bean class="org.apache.mina.integration.beans.InetSocketAddressEditor"/>
                </entry>
            </map>
        </property>
    </bean>  
需要注意的InetSocketAddressEditor是mina-integration-beans.jar包下的一個類,我們需要在pom.xml中加入這個依賴,程式碼如下
    <dependency>
        <groupId>org.apache.mina</groupId>
        <artifactId>mina-integration-beans</artifactId>
        <version>2.0.7</version>
    </dependency> 
加上這個依賴後專案會報錯,報錯資訊如下:
Failed to execute goal on project mina-test: Could not resolve dependencies for project com.snail.mina:mina-test:jar:0.0.1-SNAPSHOT:
<span style="color:#CC0000;">Failure to find org.apache.mina:mina-core:bundle:2.0.7</span> in http://10.5.1.13:8081/nexus/content/groups/public was cached in the local 
repository, resolution will not be reattempted until the update interval of nexus has elapsed or updates are forced -> [Help 1]
出現這個問題的原因是因為mina打包為bundle(這個過程我也不清楚,有興趣的同學可以百度 maven bundle)
解決辦法是在pom.xml中加入相應的外掛,程式碼如下:
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.felix</groupId>
                    <artifactId>maven-bundle-plugin</artifactId>
                    <extensions>true</extensions>
                </plugin>
            </plugins>
        </build>  
啟動本地伺服器,用Secure CRT連線本地伺服器(也可以用DOS連線,或者自己寫客戶端也可以)

控制檯輸出如下:


如有寫的不明白的地方可以在下面留言!!!
THE  END!!!



相關文章