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】获取当前时间戳importtime 获取当前时间 times datetime now strftime Y m d H M S printtimes 转为时间数组 timeArray time strptime times Y m d H M S 转为时间戳 timeStamp int time mktime timeArray printtimeSta 结果 个人网站 沉默博客如有错误 请多多指教 如对你有帮助

    2025年7月1日
    3
  • vscode常用插件推荐_梅林软件中心 常用插件

    vscode常用插件推荐_梅林软件中心 常用插件vscode插件推荐-献给所有前端工程师(2018.4.29更新)精选!15个必备的VSCode插件(前端类)30个极大提高开发效率的VisualStudioCode插件VSCode使用总结vscode几个常用插件推荐[补充]精选!15个必备的VSCode插件VSCode拓展插件推荐(HTML、Node、Vue、React开发均适用)VSCode折腾记-(4)…

    2022年9月30日
    1
  • gtest测试框架使用详解_vstest和gtest比较

    gtest测试框架使用详解_vstest和gtest比较很早就接触了googleC/C++自动化测试框架gtest,作为

    2022年9月29日
    4
  • css圆角边框怎么设置颜色_word图片怎么设置圆角大小

    css圆角边框怎么设置颜色_word图片怎么设置圆角大小总结起来很简单,设置css圆角边框就是设置border-radius的值,设置的数字不同,圆角的大小也不同。通过设计css圆角边框,我们就不需要再用带框的背景图片,这不仅让页面设计更加简单,同时也有利于提升页面加载的速度。本文给大家简单介绍下css圆角边框怎么设置,大家可以参考,也可以直接拿过去使用,当然要修改下具体的参数。上面的css代码,大家可以直接拿去用,至于像15px、50px等这些数据,大家可以通过测试看看具体需要多大数字,这里给出的数字只是参考。圆角边框的最基本用法就是设置四个相同弧度的圆角。.

    2025年8月14日
    3
  • 移动端开发基础知识「建议收藏」

    移动端开发基础知识「建议收藏」移动web开发指的是:需要适配移动设备的网页开发移动web开发与pc端web开发没有本质的区别,使用的还是HTML/CSS/JavaScript的技术移动端与pc端web开发的区别:1、浏览器不同移动端的浏览器与pc端不同谷歌浏览器苹果浏览器、UC浏览器QQ浏览器百度手机浏览器360安全浏览器搜狗浏览器猎豹浏览器等国内的手机浏览器都是根据webkit内核修…

    2022年6月24日
    27
  • jsp分页功能实现两种方法(html如何实现分页功能)

    本期的jsp入门学习内容:实现JSP分页显示的方法。今天给大家带来实现jsp分页显示的代码,简单的7个步骤就可以实现JSP的分页显示,有需要的朋友可以参考一下,学习些jsp开发的知识。正式开始此次的jsp入门教程的学习:1、MySQL的limit关键字(DAO)2、jQuery load函数(页面JS)MySQL的limit关键词能够完结抽取必定规模(n

    2022年4月17日
    274

发表回复

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

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