简单介绍:MINA框架是对java的NIO包的一个封装,简化了NIO程序开发的难度,封装了很多底层的细节,然开发者把精力集中到业务逻辑上来,最近做了一个相关的项目,为了备忘对MINA做一个总结。
下面这个start方法用来初始化MINA:
- private void start(int port, WebContext ctx)
- throws IOException, InstantiationException
- , IllegalAccessException, ClassNotFoundException {
-
- NioSocketAcceptor acceptor = new NioSocketAcceptor(5);
-
- java.util.concurrent.Executor threadPool = Executors.newFixedThreadPool(1500);
-
- acceptor.getFilterChain().addLast("exector", new ExecutorFilter(threadPool));
- acceptor.getFilterChain().addLast("codec",
- new ProtocolCodecFilter(new WebDecoder(),new WebEncoder()));
- LoggingFilter filter = new LoggingFilter();
- filter.setExceptionCaughtLogLevel(LogLevel.DEBUG);
- filter.setMessageReceivedLogLevel(LogLevel.DEBUG);
- filter.setMessageSentLogLevel(LogLevel.DEBUG);
- filter.setSessionClosedLogLevel(LogLevel.DEBUG);
- filter.setSessionCreatedLogLevel(LogLevel.DEBUG);
- filter.setSessionIdleLogLevel(LogLevel.DEBUG);
- filter.setSessionOpenedLogLevel(LogLevel.DEBUG);
- acceptor.getFilterChain().addLast("logger", filter);
-
- acceptor.setReuseAddress(true);
-
- acceptor.getSessionConfig().setReuseAddress(true);
- acceptor.getSessionConfig().setReceiveBufferSize(1024);
- acceptor.getSessionConfig().setSendBufferSize(10240);
-
- acceptor.getSessionConfig().setTcpNoDelay(true);
-
- acceptor.setBacklog(100);
- acceptor.setDefaultLocalAddress(new InetSocketAddress(port));
-
- acceptor.setHandler(new WebHandler());
- acceptor.bind();
- }
NioSocketAcceptor是MINA的适配器,一切都是从这里开始的。MINA中有个过滤器和处理器的概念,过滤器用来过滤数据,处理器用来处理数据。具体来说MINA的处理模型就是request->过滤器A->过滤器B->处理器->过滤器B->过滤器A->response,这里的request和response类似serlvet的request和response。
- acceptor.getFilterChain().addLast("exector", new ExecutorFilter(threadPool));
-
- acceptor.getFilterChain().addLast("codec",
- new ProtocolCodecFilter(new WebDecoder(),new WebEncoder()));
-
-
现在详细描述一下request->WebDecoder->WebHandler->WebEncode->response的过程:
客户端发送一个请求到MINA服务器,这里相当于来了一个requet。请求首先来到
- WebDecoder类(实现了ProtocolDecoder接口)中的
- boolean decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception{}方法
-
-
-
-
-
-
-
-
-
-
然后到
- WebHandler(扩展了IoHandlerAdapter抽象类)中的
- void messageReceived(IoSession session, Object message) throws Exception{}方法
- WriteFuture future = session.write(response);
- future.addListener(IoFutureListener.CLOSE);
- IoFutureListener里面有个operationComplete(IoFuture future)方法,当流发送完成之后才调用这个方法。
-
-
-
-
-
-
然后到
- WebEncoder类(实现了ProtocolEncoder接口)中的
- boolean encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception{}
- 方法
-
-
-
-
-
-
-