mina框架分析:总体结构分析[通俗易懂]

MINAbasedApplicationArchitectureIt’sthequestionmostasked:’Howdoesa MINA basedapplicationlooklike’?Inthisarticleletsseewhat’sthearchitectureofMINAbasedapplication.Havetr

大家好,又见面了,我是你们的朋友全栈君。

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 :

mina框架分析:总体结构分析[通俗易懂]

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 :

mina框架分析:总体结构分析[通俗易懂]


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 :

  1. Create an I/O service – Choose from already available Services (*Acceptor) or create your own
  2. Create a Filter Chain – Choose from already existing Filters or create a custom Filter for transforming request/response
  3. 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.

mina框架分析:总体结构分析[通俗易懂]

  • 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 IOHandlerIOHandlers 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.

    mina框架分析:总体结构分析[通俗易懂]

    • 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>

三者什么关系呢?

mina框架分析:总体结构分析[通俗易懂]

至于,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;



版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/126906.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Python从字符串中删除字符

    Python从字符串中删除字符Sometimeswewanttoremovealloccurrencesofacharacterfromastring.Therearetwocommonwaystoachievethis.有时我们想从字符串中删除所有出现的字符。有两种常见的方法可以实现此目的。Python从字符串中删除字符(PythonRemoveCharacterfr…

    2022年5月24日
    37
  • pxe装机「建议收藏」

    pxe装机「建议收藏」安装环境:一台已安装Linux系统的主机作为PXEServer,本文中PXEServer使用的系统是CentOS7;若干台待安装CentOS7的裸主机作为PXEClient;PXEServer与所有PXEClient处于同一局域网中;所有主机支持PXE启动安装方式。PXEServer安装及配置流程:\1.配置DHCP服务\2.配置TFTP服务\3.配…

    2022年6月16日
    32
  • js获取时间进行比较

    js获取时间进行比较现象 js 中获取时候进行比较方法 js 获取时间 昨天的时间 varday1 newDate day1 setTime day1 getTime 24 60 60 1000 vars1 day1 getFullYear day1 getMonth 1 day1 getDate 今天的时间 varday2 new

    2025年9月22日
    2
  • 特征归一化处理_归一化法要求

    特征归一化处理_归一化法要求版权声明:本文为博主原创文章,遵循CC4.0BY-SA版权协议,转载请附上原文出处链接和本声明。…

    2025年6月5日
    2
  • 词向量简介「建议收藏」

    词向量简介「建议收藏」最近深度学习技术有了突飞猛进的发展,为语音识别、图像识别、自然语言处理(NLP)提供了强大的工具,为这些领域今后的快速发展提供了新的契机。深度学习为自然语言处理带来的最令人兴奋的突破是词向量(wordembedding)技术。词向量技术是将词转化成为稠密向量,并且对于相似的词,其对应的词向量也相近。在自然语言处理应用中,词向量作为深度学习模型的特征进行输入。因此,最终模型的效果很大程度上取

    2022年6月6日
    41
  • Java Calendar获取年、月、日、时间[通俗易懂]

    Java Calendar获取年、月、日、时间[通俗易懂]Calendarc=Calendar.getInstance(TimeZone.getTimeZone(“GMT+08:00”));//获取东八区时间intyear=c.get(Calendar.YEAR);//获取年intmonth=c.get(Calendar.MONTH)+1;//获取月份,0表示1月份intday=c.get(Calend…

    2022年5月2日
    43

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号