您的位置:首页 > 其它

mina框架分析:总体结构分析

2014-09-02 15:44 260 查看


1.首先,了解下mina框架有哪些特点,适合什么样的场景

MINA is a simple yet full-featurednetwork application framework which provides:
//可以支持各种协议,包括自己的协议

Unified API for various transport types:

TCP/IP & UDP/IP via Java NIO
Serial communication (RS232) via RXTX
In-VM pipe communication
You can implement your own!

//提供滤波器接口

Filter interface as an extension point; similar to Servlet filters

//可以调用不同类型的API,低层次的有ByteBuffer,高层次的有用户自己定义消息对象

Low-level and high-level API:

Low-level: uses ByteBuffers
High-level: uses user-defined message objects and codecs

//非常个性化的线程订制,可以提供单线程,单线程池,多线程池

Highly customizable thread model:

Single thread
One thread pool
More than one thread pools (i.e. SEDA)

Out-of-the-box SSL · TLS · StartTLS support using Java 5 SSLEngine
Overload shielding & traffic throttling
Unit testability using mock objects
JMX manageability

//支持对象流

Stream-based I/O support via StreamIoHandler
Integration with well known containers such as PicoContainer and Spring

//很容易从Netty移植到mina

Smooth migration from Netty, an ancestor of Apache MINA.


2.分析mina框架结构和原理


MINA based Application Architecture

It's the question most asked : 'How does a MINA based application look like'? In this article lets see what's the architecture of MINA based application. Have tried to gather the information from presentations based
on MINA.

A Bird's Eye View :



Here, we can see that MINA is the glue between your application (be it a client or a server) and the underlying network layer, which can be based on TCP, UDP, in-VM comunication or even a RS-232C serial protocol
for a client.

You just have to design your application on top of MINA without having to handle all the complexity of the newtork layer.

Lets take a deeper dive into the details now. The following image shows a bit more the internal of MINA, and what are each of theMINA components doing :



Broadly, MINA based applications are divided into 3 layers

I/O Service - Performs actual I/O
I/O Filter Chain - Filters/Transforms bytes into desired Data Structures and vice-versa
I/O Handler - Here resides the actual business logic

So, in order to create a MINA based Application, you have to :

Create an I/O service - Choose from already available Services (*Acceptor) or create your own
Create a Filter Chain - Choose from already existing Filters or create a custom Filter for transforming request/response
Create an I/O Handler - Write business logic, on handling different messages

This is pretty much it.

You can get a bit deeper by reading those two pages :


Server Architecture

We have exposed the MINA Application Architecture in the previous section. Let's now focus on the Server Architecture. Basically, a Server listens on a port for incoming requests, process them and send replies.
It also creates and handles a session for each client (whenever we have a TCP or UDP based protocol), this will be explain more extensively in the chapter
4.



IOAcceptor listens on the network for incoming connections/packets
For a new connection, a new session is created and all subsequent request from IP Address/Port combination are handled in that Session
All packets received for a Session, traverses the Filter Chain as specified in the diagram. Filters can be used to modify the content of packets (like converting to Objects, adding/removing information etc). For converting to/from
raw bytes to High Level Objects, PacketEncoder/Decoder are particularly useful
Finally the packet or converted object lands in
IOHandler
.
IOHandler
s can be used to fulfill business needs.

Client Architecture

We had a brief look at MINA based Server Architecture, lets see how Client looks like. Clients need to connect to a Server, send message and process the responses.



Client first creates an IOConnector (MINA Construct for connecting to Socket), initiates a bind with Server
Upon Connection creation, a Session is created and is associated with Connection
Application/Client writes to the Session, resulting in data being sent to Server, after traversing the Filter Chain
All the responses/messages received from Server are traverses the Filter Chain and lands at IOHandler, for processing

Of course, MINA offers more than just that, and you will robably have to take care of many oher aspects,like the messages encoding/decoding, the network configuration how to scale up, etc...(这一块对于写程序其实更重要)
We will have a further look at those aspects in the next chapters.

知道了mina的大致框架,那么下面就从源码去分析具体是如何实现的。

以server结构为例说明

1.IoAcceptor

说明:Accepts incoming connection, communicates with clients, and fires events to {@link IoHandler}s.



IoAcceptor和IoConnector接口都继承IoService的接口

Ioservice接口提供的方法主要有:

Server listens on a portfor incoming requests, process them and send replies

监听事件:void addListener(IoServiceListener listener);

处理接口;IoHandler getHandler();

返回一些数据;TransportMetadata getTransportMetadata();

管理session:IoSessionConfig getSessionConfig();

IoAcceptor的主要方法有:

Socket地址管理
SocketAddress getLocalAddress();

端口绑定 void bind(SocketAddress firstLocalAddress, SocketAddress...addresses) throws IOException;

IoSession管理 IoSession newSession(SocketAddress remoteAddress, SocketAddresslocalAddress);

2.下一步就是看session了

Session类的说明:A handle which represents connection between two end-pointsregardless of transport types.

需要注意的是:IoSessionis thread-safe。But please note that performing more than one {@link #write(Object)} calls atthe same time will cause the {@linkIoFilter#filterWrite(IoFilter.NextFilter,IoSession,WriteRequest)} to beexecuted
simultaneously, and therefore you have to make sure the {@linkIoFilter} implementations you're using are thread-safe, too.(要确保你重写的IoFilter必须是线程安全的)

里面重要的几个成员:(基本跟管理session,发送数据有关)

IoFilterChaingetFilterChain();//返回影响该session的filter chain

ObjectgetAttribute(Object key);//用户可以设置自己的attribution,对应的有setAtrribute

long getReadBytes();//返回从session里面读出的字节总数

long getWrittenBytes();//返回已经写到session里面的字节总数

booleanisWriterIdle();//判断session是否写空闲

3.下一步就是看filter了

IoFilterChain(他不是继承IoFilter哦)

说明:Acontainer of {@link IoFilter}s that forwards {@link IoHandler} events to theconsisting filters and terminal {@link IoHandler} sequentially.

IoFilterAdapter

继承于IoFilter

说明:Anadapter class for {@link IoFilter}. Youcan extend this class and selectively override required event filter methodsonly. All methods forwards events to thenext filter by default.

IoFilter

说明:

Afilter which intercepts {@link IoHandler} events like Servlet filters. Filters can be used for these purposes:

* <li>Event logging,</li>

* <li>Performance measurement,</li>

* <li>Authorization,</li>

* <li>Overload control,</li>

* <li>Message transformation (e.g. encryption and decryption,...),</li>

* <li>and many more.</li>

三者什么关系呢?



至于,IoFilterChain去管理和分发Filter事件

问题1:如何实现自己的Filter类呢?

mina框架本身也提供了几个filter,如

1、LoggingFilter :日志过滤器,用于记录所有的事件和请求日志.

2、ProtocolCodecFilter:规约解析过滤器,用来将所有收到的ByteBuffer内容转换为POJO消息(对象),实现往来报文的编码和解码;

3、CompressionFilter:压缩过滤器;

4、SSLFilter

要想写自己的filter,可以参考一个白名单的例子: http://blog.csdn.net/kingmicrosoft/article/details/39153101
具体的Filter原理见
http://blog.csdn.net/kingmicrosoft/article/details/39151581
4.下一个就是Iohander了

说明:Handles all I/O events fired by MINA

Invoked from an I/O processor threadwhen a new connection has been created.

主要的成员是:

voidsessionOpened(IoSession session) throws Exception;//session打开后被触发

void sessionClosed(IoSession session)throws Exception;//session关闭后被触发

//收到信息后被触发

void messageReceived(IoSession session,Object message) throws Exception;

//当信息被IoSession#write(Object)写完后触发

void messageSent(IoSession session,Object message) throws Exception;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: