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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • rabbitmq实例_rabbitmq创建队列

    rabbitmq实例_rabbitmq创建队列RabbitMQ简介RabbitMQ是一个受欢迎的消息代理,通常用于应用程序之间或者程序的不同组件之间通过消息来进行集成。具有高可用高并发的优点,适合集群服务器。采用Erlang实现,对主要的编程语言都有客户端支持。RabbitMQ环境配置linux下环境配置我用的是centos6.5版本。先从这个地址下载安装包下载地址$tar-zxvfotp_…

    2022年9月26日
    0
  • phpstorm 2021 激活码3月最新在线激活

    phpstorm 2021 激活码3月最新在线激活,https://javaforall.net/100143.html。详细ieda激活码不妨到全栈程序员必看教程网一起来了解一下吧!

    2022年3月15日
    61
  • MyBatis-Plus 之分页查询

    MyBatis-Plus 之分页查询MyBatis-Plus之分页查询首先创建一个数据库表,如下图所示:然后创建一个SpringBoot项目,pom.xml和配置如下:<?xmlversion=”1.0″encoding=”UTF-8″?><projectxmlns=”http://maven.apache.org/POM/4.0.0″xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”xsi:schemaLoc

    2022年6月2日
    38
  • c++一些常用的数学函数

    c++一些常用的数学函数

    2021年9月27日
    71
  • 自定义Python排序函数比较方式

    自定义Python排序函数比较方式当你想按自己的方式对数组元素进行排序时,我们需要自定义比较函数实现我们想实现的排序方式。例1以降序对数组进行排序>>>defcomp(x,y):…returny-x…>>>a=[1,8,4,5,2,7]>>>a.sort(comp)>>>a[8,7,5,4,2,1…

    2025年6月25日
    0
  • openCV人脸识别简单案例[通俗易懂]

    openCV人脸识别简单案例[通俗易懂]1基础我们使用机器学习的方法完成人脸检测,首先需要大量的正样本图像(面部图像)和负样本图像(不含面部的图像)来训练分类器。我们需要从其中提取特征。下图中的Haar特征会被使用,就像我们的卷积核,每一个特征是一个值,这个值等于黑色矩形中的像素值之后减去白色矩形中的像素值之和。Haar特征值反映了图像的灰度变化情况。例如:脸部的一些特征能由矩形特征简单的描述,眼睛要比脸颊颜色要深,鼻梁两侧比鼻梁颜色要深,嘴巴比周围颜色要深等。Haar特征可用于于图像任意位置,大小也可以任意改变,所以矩形特征值是

    2022年5月28日
    46

发表回复

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

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