Example of using mina

Source: Internet
Author: User
Summary of use of the MINA framework

Reference: http://xinsync.xju.edu.cn/index.php/archives/category/prglang/java/mina

Brief Introduction: MINA
The framework encapsulates java NIO packages, which simplifies the development difficulty of NIO programs and encapsulates many underlying details. However, developers concentrate on business logic, recently, a related project has been developed
Make a summary.

The following start method is used to initialize MINA.
:

Java code
  1. Private
     
    Void
    Start (
    Int
    Port, webcontext CTX)

  2. Throws
    Ioexception, instantiationexception
  3. , IllegalAccessException, ClassNotFoundException {

  4. // Initialize the Acceptor
  5. NioSocketAcceptor acceptor =
    New
    NioSocketAcceptor (
    5
    );
  6. Java. util. concurrent. Executor threadPool = Executors. newFixedThreadPool (
    1500
    );
    // Create a thread pool

  7. // Add a Filter to the Acceptor.
  8. Acceptor. getFilterChain (). addLast (
    "Exector"
    ,
    New
    ExecutorFilter (threadPool ));
  9. Acceptor. getFilterChain (). addLast (
    "Codec"
    ,

  10. New
    ProtocolCodecFilter (
    New
    WebDecoder (),
    New
    WebEncoder ()));
  11. LoggingFilter filter =
    New
    LoggingFilter ();
  12. Filter. setExceptionCaughtLogLevel (LogLevel. DEBUG );
  13. Filter. setMessageReceivedLogLevel (LogLevel. DEBUG );
  14. Filter. setMessageSentLogLevel (LogLevel. DEBUG );
  15. Filter. setSessionClosedLogLevel (LogLevel. DEBUG );
  16. Filter. setSessionCreatedLogLevel (LogLevel. DEBUG );
  17. Filter. setSessionIdleLogLevel (LogLevel. DEBUG );
  18. Filter. setSessionOpenedLogLevel (LogLevel. DEBUG );
  19. Acceptor. getFilterChain (). addLast (
    "Logger"
    , Filter );
  20. Acceptor. setReuseAddress (
    True
    );
    // Set the listening port of the master service to be reused.
  21. Acceptor. getSessionConfig (). setReuseAddress (
    True
    );
    // Set the port for each non-master listener connection to be reused.
  22. Acceptor. getSessionConfig (). setReceiveBufferSize (
    1024
    );
    // Set the input buffer size
  23. Acceptor. getSessionConfig (). setSendBufferSize (
    10240
    );
    // Set the size of the output buffer.
  24. // Set to non-delayed sending. If it is set to true, it is not encapsulated into a large package for sending. The message is sent immediately after receiving the message.
  25. Acceptor. getSessionConfig (). setTcpNoDelay (
    True
    );
  26. // Set the maximum value of the listening queue on the listening port of the primary service to 100. If there are already 100 connections, the new connection will be rejected by the server.
  27. Acceptor. setBacklog (
    100
    );
  28. Acceptor. setdefalocallocaladdress (
    New
    InetSocketAddress (port ));

  29. // Add the processor (Handler) to the Acceptor
  30. Acceptor. setHandler (
    New
    WebHandler ());
  31. Acceptor. bind ();
  32. }
Private void start (int port, WebContext ctx) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {// initialize AcceptorNioSocketAcceptor acceptor = new NioSocketAcceptor (5); java. util. concurrent. executor threadPool = Executors. newFixedThreadPool (1500); // create a thread pool // Add the Filter to Acceptoracceptor. 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); // you can use the acceptor to set the listening port of the master service. getSessionConfig (). setReuseAddress (true); // you can use the acceptor to set the port of a non-master listener connection. getSessionConfig (). setReceiveBufferSize (1024); // set the size of the input buffer acceptor. getSessionConfig (). setSendBufferSize (10240); // you can specify the size of the output buffer. // if this parameter is set to true, the output buffer is not sent in a large package. When this parameter is set to true, an acceptor is sent immediately after receiving the message. getSessionConfig (). setTcpNoDelay (true); // set the maximum value of the listening queue on the listening port of the master service to 100. If there are already 100 connections, the server rejects the acceptor after a new connection. setBacklog (100); acceptor. setdefalocallocaladdress (new InetSocketAddress (port); // Add the processor (Handler) to Acceptoracceptor. setHandler (new WebHandler (); acceptor. bind ();}

NioSocketAcceptor is MINA
And everything starts from here. MINA
There is a concept of filters and processors. filters are used to filter data and processors are used to process data. Specifically, MINA
The processing model of is request-> filter A-> filter B-> processor-> filter B-> filter A-> response. The request and response here are similar to the request and response of serlvet.

Java code
  1. Acceptor. getFilterChain (). addLast (
    "Exector"
    ,
    New
    ExecutorFilter (threadPool ));
  2. // Add a thread pool to the adapter. the built-in jdk thread pool is used here.
Acceptor. getFilterChain (). addLast ("exector", new ExecutorFilter (threadPool); // Add a thread pool to the adapter, where the built-in jdk thread pool is used.

 

Java code
  1. Acceptor. getfilterchain (). addlast (
    "Codec"
    ,

  2. New
    Protocolcodecfilter (
    New
    Webdecoder (),
    New
    Webencoder ()));
  3. //
    Here is the key part of the processing logic. The request is processed in the webdecoder class and webencoder class. It can be seen from the name that one is used for decoding and the other is used for decoding.
    After requet comes in, it first enters the webdecoder class (implements the protocoldecoder Interface) for decoding. Here you can add your own logic to pass in
    The stream is decoded into the desired information. The webencoder class (which implements the protocolencoder Interface) is encoded. In this class, add your own logic to encode the processed information.
    Assemble and send it to the client (response ). In the process of decoding and encoding, webhandler (Extended iohandleradapter abstract class) starts to work as a processor.
    .
  4. // Request-> webdecoder-> webhandler-> webencode-> response
Acceptor. getFilterChain (). addLast ("codec", new ProtocolCodecFilter (new WebDecoder (), new WebEncoder (); // here is the key part of the processing logic, requests are processed in the WebDecoder class and WebEncoder class. It can be seen from the name that one is used for decoding and the other is used for encoding, after requet arrives, it first enters the WebDecoder class (implements the ProtocolDecoder Interface) for decoding. Here, you can add your own logic to decode the transmitted stream into the desired information. The WebEncoder class (which implements the ProtocolEncoder Interface) is encoded. In this class, add your own logic to assemble the processed information and send it to the client (response ). In the process of decoding and encoding, WebHandler (which extends the IoHandlerAdapter abstract class) plays the role of the processor. // Request-> WebDecoder-> WebHandler-> WebEncode-> response

 

Here we will describe the request-> WebDecoder-> WebHandler-> WebEncode-> response process in detail:

The client sends a request to MINA.
Server, which is equivalent to a requet. Request comes first

Java code
  1. In the webdecoder class (which implements the protocoldecoder Interface)
  2. Boolean
    Decode (IoSession session, IoBuffer in, ProtocolDecoderOutput out)
    Throws
    Exception {} Method
  3. /*
     
  4. Parameter in: all user request information exists here. Read data is read from in.
     
  5. Parameter out: Used to output the processed data to the next Filter of the Filter. If there is no Filter, it is output to WebHandler.
     
  6. Servelt filters are similar. Use the out. write (Object object) function to upload data to the next Filter. We can define it ourselves
     
  7. An object. We assume it is a Request and use it to transmit messages. Then we can write out. write (new RequsetMessage () here ());
     
  8. If this method returns false, that is, the current logical package has not been fully received (that is, the current IoBuffer does not contain enough data), you need
     
  9. Run the decode method (obtain the new IoBuffer again) to obtain enough data. If the return value is true, the decode side is not executed.
     
  10. But to activate the handler method, you must call the out. write method.
     
  11. Public class requestmessage {} // nothing here
     
  12. */

Boolean decode (IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {} method/* parameter in the WebDecoder class (which implements the ProtocolDecoder Interface): all user request information exists here, read data from in. Parameter out: Used to output the processed data to the next Filter of the Filter. If there is no Filter, it is output to WebHandler, which is a bit similar to the servelt Filter. Use the out. write (Object object) function to upload data to the next Filter. We can define an object by ourselves. We assume that the Request is used to transmit the message. Then we can write it as out. write (new RequsetMessage (); if this method returns false, it means that the current logical package has not been fully received (that is, the current IoBuffer does not contain enough data ), run the decode method again (obtain the new IoBuffer again) to obtain enough data. If the return value is true, the decode method is not executed. to activate the handler method, you must call the out. write method. Public class RequestMessage {} // nothing here */

Then go

Java code
  1. Webhandler (extends the iohandleradapter abstract class)
  2. Void
    Messagereceived (iosession session, object message)
    Throws
    Exception {} Method
  3. Writefuture future = session. Write (response );
    // This code must be added to the session to activate the encode method.
  4. Future. addlistener (iofuturelistener. Close );
    // This function is to close the connection after sending the message. If the connection is added, it is a short connection. Otherwise, it is a long connection.
  5. There is an operationcomplete (iofuture future) method in iofuturelistener. This method is called only after the stream is sent.
  6. /*
     
  7. Parameter message: used to obtain the object passed by the filter. The corresponding code requestmessage request = (requestmessage) message;
     
  8. Parameter session: used to send data to the Filter. corresponding code session. write (new ResponseMessage ());
     
  9. Public class ResponseMessage {} // nothing is done here. Assume that the processed data is stored.
     
  10. Note: For a MINA
    For programs, the WebHandler class generates only one object, so thread security issues must be considered.
     
  11. */

Void messagereceived (iosession session, object message) in webhandler (Extended iohandleradapter abstract class) throws exception {} method writefuture future = session. write (response); // This code must be added to the session to activate the encode method future. addlistener (iofuturelistener. close); // the function of this operation is to close the connection after sending. If a short connection is added, the operationcomplete (iofuture future) method is provided in the iofuturelistener, this method is called only after the stream is sent. /* Parameter message: used to obtain the object passed by the filter. corresponding code: requestmessage request = (requestmessage) message; parameter session: used to send data to the filter. corresponding code session. write (New responsemessage (); public class responsemessage {} // nothing here. Assume that the processed data is stored. Note: For a mina program, only one object is generated for the webhandler class, so thread security issues should be considered */

 

Then go

Java code
  1. In the WebEncoder class (which implements the ProtocolEncoder Interface)
  2. Boolean
    Encode (IoSession session, Object message, ProtocolEncoderOutput out)
    Throws
    Exception {}
  3. Method
  4. /*
     
  5. Parameter message: used to obtain the data of the previous Filter node or the data of the processor (if the Filter is the one closest to the processor)
     
  6. ResponseMessage response = (ResponseMessage) message;
     
  7. Parameter out: Used to output data to the next Filter node or to the client. The data is sent using out. write (Object encodedMessage ).
     
  8. If the next Filter node is a client, the encodedMessage data must be
     
  9. For the IoBuffer type, you can use IoBuffer. wrap (byte [] byteArray) to format the output data.
     
  10. */
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.