Mina主要是作为服务器端底层框架来实现数据处理,它的实现很简单,如下例所示:
package com.gftech.mytool.mina; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; public class MinaTimeServer { private static final int PORT = 2500; //调用工厂方法,得到一个日志记录器,我用的是自己最熟悉的Log4j //slf4j本身是一个Facade,或者说象集群服务中的分发器,它本身没有Logger的记录功能 //它会自动根据Classpath中的具体Logger类库来实现具体调用,在LoggerFactory实例化Logger static Logger logger = LoggerFactory.getLogger(MinaTimeServer.class); public static void main(String[] args) throws IOException { //在服务器端创建一个接收器 IoAcceptor acceptor = new NioSocketAcceptor(); //创建一个日志过滤器进行日志处理,并添加到过滤器链的第一个位置 //过滤器的位置很重要,在这里因为放到了第一个位置,它会记录原始字节码数据 LoggingFilter lf = new LoggingFilter("testLog"); acceptor.getFilterChain().addLast("logger", lf); //增加一个按行进行处理文本的编解码过滤器,并且指定按GBK的方法进行编解码 acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("GBK")))); //进行配置信息的设置 acceptor.getSessionConfig().setReadBufferSize(10); acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10); //添加一个数据处理器,对接收或发送的数据进行处理 acceptor.setHandler(new TimeServerHandler()); //把IoAccepter绑定到指定的2500端口 acceptor.bind(new InetSocketAddress(PORT)); System.out.println("start server ..."); } } class TimeServerHandler extends IoHandlerAdapter { static Logger logger = LoggerFactory.getLogger(TimeServerHandler.class); //static Logger logger = Logger.getLogger(TimeServerHandler.class); //异常处理 public void exceptionCaught(IoSession session, Throwable cause) throws Exception { cause.printStackTrace(); } //对接收到的数据进行业务处理,在这里我们不管收到什么信息都返回一个当前的日期 public void messageReceived(IoSession session, Object message) throws Exception { String str = message.toString(); if (str.trim().equalsIgnoreCase("quit")) { session.close(true); return; } logger.debug("Rec:" + str); Date date = new Date(); session.write(date.toString()); logger.debug("Message written..."); } //当连接空闲时的处理 public void sessionIdle(IoSession session, IdleStatus status) throws Exception { logger.debug("IDLE " + session.getIdleCount(status)); } }
在上面的代码中,我用了mina默认的SLF4J日志处理器。因为slf4j本身没有真正的日志处理功能,它最终调用的是log4j,所以我们可以编写一下log4j的配置文件来指定具体的输出方式。需要注意的一点是配置文件必须放在src文件夹下面,否则slf4j无法找到,示例如下:
log4j.rootLogger =DEBUG, A1,A2 #输出到控制台 log4j.appender.A1 = org.apache.log4j.ConsoleAppender log4j.appender.A1.layout = org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern =[%d] [%t] %-5p - %m %n #输出到固定大小的日志文件 log4j.appender.A2 = org.apache.log4j.RollingFileAppender log4j.appender.A2.File = logs//test1.log log4j.appender.A2.MaxFileSize = 1MB log4j.appender.A2.MaxBackupIndex = 3 log4j.appender.A2.layout = org.apache.log4j.PatternLayout log4j.appender.A2.layout.ConversionPattern =[%d] %-4r [%t] %-5p %c %x - %m %n #定义A3输出到数据库 log4j.appender.A3 = org.apache.log4j.jdbc.JDBCAppender log4j.appender.A3.BufferSize = 40 log4j.appender.A3.Driver = sun.jdbc.odbc.JdbcOdbcDriver log4j.appender.A3.URL = jdbc:ODBC:driver={Microsoft Access Driver (*.mdb)};DBQ=MobileDB.mdb log4j.appender.A3.User = log4j.appender.A3.Password = log4j.appender.A3.layout = org.apache.log4j.PatternLayout log4j.appender.A3.layout.ConversionPattern = INSERT INTO log4j(createDate, thread, priority, category, message) values('%d', '%t', '%-5p', '%c', '%m') #输出到HTML文件当中,并按日期自动分割 log4j.appender.A4 = org.apache.log4j.DailyRollingFileAppender log4j.appender.A4.File = logs//log.html log4j.appender.A4.DatePattern='.'yyyy-MM-dd-HH'.html' log4j.appender.A4.layout = org.apache.log4j.HTMLLayout #A5 send log info to remote mysql database log4j.appender.A5 = com.gftech.log4j.JDBCExtAppender log4j.appender.A5.Driver = com.mysql.jdbc.Driver log4j.appender.A5.URL = jdbc:mysql://192.168.10.1:3306/log log4j.appender.A5.User = root log4j.appender.A5.Password = plus log4j.appender.A5.layout = org.apache.log4j.PatternLayout log4j.appender.A5.sql = INSERT INTO app_log(machine,occur_date,thread_name,cat,level,info) values('DP','%d{yyyy-MM-dd HH:mm:ss}','%t','%c','%p','%m') #A6 send log info(ERROR or Fatal) by Email log4j.appender.A6 = com.gftech.log4j.SMTPExtAppender log4j.appender.A6.Threshold=FATAL log4j.appender.A6.SMTPHost=smtp.126.com log4j.appender.A6.to=sinboy@126.com log4j.appender.A6.from=sinboy@126.com log4j.appender.A6.SMTPAuth=true log4j.appender.A6.SMTPUsername=sinboy log4j.appender.A6.SMTPPassword=123456 log4j.appender.A6.Subject=Log4J Message log4j.appender.A6.layout=org.apache.log4j.PatternLayout log4j.appender.A6.layout.ConversionPattern= [%d{HH:mm:ss}] [%t] %c - %-5p - %m%n
在命令行终端输入:telnet 127.0.0.1 2500可以进行测试,当然也可以自己模拟多个客户端进行并发访问测试mina的真实性能。我在P4/512M的机器上测出的结果是每秒可以处理1700~2000个数据,,根据并发客户端的多少会有不同。