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
- Private
Void
Start (
Int
Port, webcontext CTX)
Throws
Ioexception, instantiationexception
- , IllegalAccessException, ClassNotFoundException {
// Initialize the Acceptor
- NioSocketAcceptor acceptor =
New
NioSocketAcceptor (
5
);
- Java. util. concurrent. Executor threadPool = Executors. newFixedThreadPool (
1500
);
// Create a thread pool
// Add a Filter to the Acceptor.
- Acceptor. 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
);
// Set the listening port of the master service to be reused.
- Acceptor. getSessionConfig (). setReuseAddress (
True
);
// Set the port for each non-master listener connection to be reused.
- Acceptor. getSessionConfig (). setReceiveBufferSize (
1024
);
// Set the input buffer size
- Acceptor. getSessionConfig (). setSendBufferSize (
10240
);
// Set the size of the output buffer.
- // 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.
- Acceptor. getSessionConfig (). setTcpNoDelay (
True
);
- // 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.
- Acceptor. setBacklog (
100
);
- Acceptor. setdefalocallocaladdress (
New
InetSocketAddress (port ));
// Add the processor (Handler) to the Acceptor
- Acceptor. setHandler (
New
WebHandler ());
- Acceptor. bind ();
- }
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
- Acceptor. getFilterChain (). addLast (
"Exector"
,
New
ExecutorFilter (threadPool ));
- // 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
- Acceptor. getfilterchain (). addlast (
"Codec"
,
New
Protocolcodecfilter (
New
Webdecoder (),
New
Webencoder ()));
- //
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.
.
- // 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
- In the webdecoder class (which implements the protocoldecoder Interface)
- Boolean
Decode (IoSession session, IoBuffer in, ProtocolDecoderOutput out)
Throws
Exception {} Method
- /*
- Parameter in: all user request information exists here. Read data is read 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.
- Servelt filters are similar. Use the out. write (Object object) function to upload data to the next Filter. We can define it ourselves
- An object. We assume it is a Request and use it to transmit messages. Then we can write out. write (new RequsetMessage () here ());
- 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
- 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.
- But to activate the handler method, you must call the out. write method.
- Public class requestmessage {} // nothing here
- */
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
- Webhandler (extends the iohandleradapter abstract class)
- Void
Messagereceived (iosession session, object message)
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 );
// 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.
- There is an operationcomplete (iofuture future) method in iofuturelistener. This method is called only after the stream is sent.
- /*
- Parameter message: used to obtain the object passed by the filter. The 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 is done here. Assume that the processed data is stored.
- Note: For a MINA
For programs, the WebHandler class generates only one object, so thread security issues must be considered.
- */
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
- In the WebEncoder class (which implements the ProtocolEncoder Interface)
- Boolean
Encode (IoSession session, Object message, ProtocolEncoderOutput out)
Throws
Exception {}
- Method
- /*
- 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)
- ResponseMessage response = (ResponseMessage) message;
- Parameter out: Used to output data to the next Filter node or to the client. The data is sent using out. write (Object encodedMessage ).
- If the next Filter node is a client, the encodedMessage data must be
- For the IoBuffer type, you can use IoBuffer. wrap (byte [] byteArray) to format the output data.
- */