Apache Mina使用手记(三)

Apache Mina使用手记(三)

分类: JAVA 2009-03-13 20:10 12752人阅读 评论(0) 收藏 举报

minaapacheexceptionsessionlog4jslf4j

在上一篇中,通过一个简单的例子,得以管中窥豹,了解了Mina的基本编写方法。在MinaTimeServer演示程序中,我们添加了两个过滤器,一个是日志过滤器LoggingFilter,一个是文本编解码过滤器。前者实现日志信息的自动处理,后者实现对按行读写的文本数据的编码和解码。

其中LoggingFilter默认的是slf4j,它是一个日志Facade,实际并不实现真正的日志处理功能,它在程序运行时自动判断classpath中加载的日志组件,比如:log4j/Logback/JUL等,确定之后调用真正的日志组件实现真正的日志处理操作。这一点对于组件式的程序,很明显是非常灵活的,因为你并不知道用户的实际环境中使用的是log4j还是JUL,或者是Logback等,但是为了实现自动识别,slf4j默认了log配置文件的加载位置,让我觉得十分不便。

我自己的所有系统中,都使用是log4j(他的替代产品Logback已经出来了,据说性能更强),我一般喜欢把所有配置文件包括log4j.properties都放在conf目录下,以便管理。因此,对于slf4j中需要把log4j.properties放在src文件夹下非常不习惯,对于以后管理也容易引起混乱。所以,我希望能直接实现自己的log4j过滤器,按以前的方式使用。我们观察一下LoggingFilter过滤器的源代码,如下所示:

public class LoggingFilter extends IoFilterAdapter{...}

LoggingFilter继承自IoFilterAdapter,它是java模型中的适配器模式,是对接口IoFilter的包装。我们可以模仿LoggingFilter,实现自己的Log4jFilter类:

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;
import org.apache.mina.filter.logging.LogLevel;
import org.slf4j.helpers.MessageFormatter;
public class Log4jFilter extends IoFilterAdapter {
    /** The logger name */
    private final String name;

    /** The logger */
    private final Logger logger;

    /** The log level for the exceptionCaught event. Default to WARN. */
    private LogLevel exceptionCaughtLevel = LogLevel.WARN;

    /** The log level for the messageSent event. Default to INFO. */
    private LogLevel messageSentLevel = LogLevel.INFO;

    /** The log level for the messageReceived event. Default to INFO. */
    private LogLevel messageReceivedLevel = LogLevel.INFO;

    /** The log level for the sessionCreated event. Default to INFO. */
    private LogLevel sessionCreatedLevel = LogLevel.INFO;

    /** The log level for the sessionOpened event. Default to INFO. */
    private LogLevel sessionOpenedLevel = LogLevel.INFO;

    /** The log level for the sessionIdle event. Default to INFO. */
    private LogLevel sessionIdleLevel = LogLevel.INFO;

    /** The log level for the sessionClosed event. Default to INFO. */
    private LogLevel sessionClosedLevel = LogLevel.INFO;

    /**
     * Default Constructor.
     */
    public Log4jFilter(Logger logger) {
        this.logger=logger;
        this.name=logger.getName();
    }

    /**
     * @return The logger's name
     */
    public String getName() {
        return name;
    }

    /**
     * Log if the logger and the current event log level are compatible. We log
     * a message and an exception.
     *
     * @param eventLevel the event log level as requested by the user
     * @param message the message to log
     * @param cause the exception cause to log
     */
    private void log(LogLevel eventLevel, String message, Throwable cause) {
        if (eventLevel == LogLevel.TRACE) {
            logger.trace(message, cause);
        } else if (eventLevel.getLevel() > LogLevel.INFO.getLevel()) {
            logger.info(message, cause);
        } else if (eventLevel.getLevel() > LogLevel.WARN.getLevel()) {
            logger.warn(message, cause);
        } else if (eventLevel.getLevel() > LogLevel.ERROR.getLevel()) {
            logger.error(message, cause);
        }
    }
    /**
     * Log if the logger and the current event log level are compatible. We log
     * a formated message and its parameters.
     *
     * @param eventLevel the event log level as requested by the user
     * @param message the formated message to log
     * @param param the parameter injected into the message
     */
    private void log(LogLevel eventLevel, String message, Object param) {
        String msgStr = MessageFormatter.format(message, param);
        if (eventLevel == LogLevel.TRACE) {
            logger.log(name, Level.TRACE, msgStr, null);

        } else if (eventLevel.getLevel() > LogLevel.INFO.getLevel()) {
            logger.log(name, Level.INFO, msgStr, null);
        } else if (eventLevel.getLevel() > LogLevel.WARN.getLevel()) {
            logger.log(name, Level.WARN, msgStr, null);
        } else if (eventLevel.getLevel() > LogLevel.ERROR.getLevel()) {
            logger.log(name, Level.ERROR, msgStr, null);
        }
    }
    /**
     * Log if the logger and the current event log level are compatible. We log
     * a simple message.
     *
     * @param eventLevel the event log level as requested by the user
     * @param message the message to log
     */
    private void log(LogLevel eventLevel, String message) {
        if (eventLevel == LogLevel.TRACE) {
            logger.trace(message);
        } else if (eventLevel.getLevel() > LogLevel.INFO.getLevel()) {
            logger.info(message);
        } else if (eventLevel.getLevel() > LogLevel.WARN.getLevel()) {
            logger.warn(message);
        } else if (eventLevel.getLevel() > LogLevel.ERROR.getLevel()) {
            logger.error(message);
        }
    }
    @Override
    public void exceptionCaught(NextFilter nextFilter, IoSession session,
            Throwable cause) throws Exception {
        log(exceptionCaughtLevel, "EXCEPTION :", cause);
        nextFilter.exceptionCaught(session, cause);
    }
    @Override
    public void messageReceived(NextFilter nextFilter, IoSession session,
            Object message) throws Exception {
        log(messageReceivedLevel, "RECEIVED: {}", message );
        nextFilter.messageReceived(session, message);
    }
    @Override
    public void messageSent(NextFilter nextFilter, IoSession session,
            WriteRequest writeRequest) throws Exception {
        log(messageSentLevel, "SENT: {}", writeRequest.getMessage() );
        nextFilter.messageSent(session, writeRequest);
    }
    @Override
    public void sessionCreated(NextFilter nextFilter, IoSession session)
            throws Exception {
        log(sessionCreatedLevel, "CREATED");
        nextFilter.sessionCreated(session);
    }
    @Override
    public void sessionOpened(NextFilter nextFilter, IoSession session)
    throws Exception {
        log(sessionOpenedLevel, "OPENED");
        nextFilter.sessionOpened(session);
    }
    @Override
    public void sessionIdle(NextFilter nextFilter, IoSession session,
            IdleStatus status) throws Exception {
        log(sessionIdleLevel, "IDLE");
        nextFilter.sessionIdle(session, status);
    }
    @Override
    public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception {
        log(sessionClosedLevel, "CLOSED");
        nextFilter.sessionClosed(session);
    }

    /**
     * Set the LogLevel for the ExceptionCaught event.
     *
     * @param level The LogLevel to set
     */
    public void setExceptionCaughtLoglevel(LogLevel level) {
        exceptionCaughtLevel = level;
    }

    /**
     * Get the LogLevel for the ExceptionCaught event.
     *
     * @return The LogLevel for the ExceptionCaught eventType
     */
    public LogLevel getExceptionCaughtLoglevel() {
        return exceptionCaughtLevel;
    }

    /**
     * Set the LogLevel for the MessageReceived event.
     *
     * @param level The LogLevel to set
     */
    public void setMessageReceivedLoglevel(LogLevel level) {
        messageReceivedLevel = level;
    }

    /**
     * Get the LogLevel for the MessageReceived event.
     *
     * @return The LogLevel for the MessageReceived eventType
     */
    public LogLevel getMessageReceivedLoglevel() {
        return messageReceivedLevel;
    }

    /**
     * Set the LogLevel for the MessageSent event.
     *
     * @param level The LogLevel to set
     */
    public void setMessageSentLoglevel(LogLevel level) {
        messageSentLevel = level;
    }

    /**
     * Get the LogLevel for the MessageSent event.
     *
     * @return The LogLevel for the MessageSent eventType
     */
    public LogLevel getMessageSentLoglevel() {
        return messageSentLevel;
    }

    /**
     * Set the LogLevel for the SessionCreated event.
     *
     * @param level The LogLevel to set
     */
    public void setSessionCreatedLoglevel(LogLevel level) {
        sessionCreatedLevel = level;
    }

    /**
     * Get the LogLevel for the SessionCreated event.
     *
     * @return The LogLevel for the SessionCreated eventType
     */
    public LogLevel getSessionCreatedLoglevel() {
        return sessionCreatedLevel;
    }

    /**
     * Set the LogLevel for the SessionOpened event.
     *
     * @param level The LogLevel to set
     */
    public void setSessionOpenedLoglevel(LogLevel level) {
        sessionOpenedLevel = level;
    }

    /**
     * Get the LogLevel for the SessionOpened event.
     *
     * @return The LogLevel for the SessionOpened eventType
     */
    public LogLevel getSessionOpenedLoglevel() {
        return sessionOpenedLevel;
    }

    /**
     * Set the LogLevel for the SessionIdle event.
     *
     * @param level The LogLevel to set
     */
    public void setSessionIdleLoglevel(LogLevel level) {
        sessionIdleLevel = level;
    }

    /**
     * Get the LogLevel for the SessionIdle event.
     *
     * @return The LogLevel for the SessionIdle eventType
     */
    public LogLevel getSessionIdleLoglevel() {
        return sessionIdleLevel;
    }

    /**
     * Set the LogLevel for the SessionClosed event.
     *
     * @param level The LogLevel to set
     */
    public void setSessionClosedLoglevel(LogLevel level) {
        sessionClosedLevel = level;
    }
    /**
     * Get the LogLevel for the SessionClosed event.
     *
     * @return The LogLevel for the SessionClosed eventType
     */
    public LogLevel getSessionClosedLoglevel() {
        return sessionClosedLevel;
    }
}

其实代码很类似,在MinaTimeServer中使用Log4jFilter使使看:

package com.gftech.mytool.mina;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.Date;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
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;
    // static Logger logger = LoggerFactory.getLogger(MinaTimeServer.class);
    static Logger logger = Logger.getLogger(MinaTimeServer.class);
    public static void main(String[] args) throws IOException {
        PropertyConfigurator.configure("conf//log4j.properties");
        IoAcceptor acceptor = new NioSocketAcceptor();
        // LoggingFilter lf = new LoggingFilter("testLog");
        Log4jFilter lf = new Log4jFilter(logger);
        acceptor.getFilterChain().addLast("logger", lf);
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("GBK"))));
        acceptor.setHandler(new TimeServerHandler());
        acceptor.getSessionConfig().setReadBufferSize(10);
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        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);
    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
    @Override
    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...");
    }
    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        logger.debug("IDLE " + session.getIdleCount(status));
    }
}

把配置文件按照自己的习惯放到conf目录下,就可以正常使用了。

需要注意的是,增加了自己的Log4jFilter之后,只能在您自己的代码中实现logger.debug()之类的调用时产生的日志记录才是正常的,即按配置文件中的要求老老实实进行日志记录。对于Mina代码中用到的logger调用,因为还是用的默认的slf4j,找不到src目录下的log4j.properties,所以产生的日志将无法正确显示和记录。除非您自己的将mina源代码中的logger全部改成log4j的logger,这是个小小的遗憾,鱼和熊掌不能兼得呀。

下一篇中,我们将介绍,如何编写自己的编解码过滤器。

时间: 2024-10-26 01:08:17

Apache Mina使用手记(三)的相关文章

Apache Mina使用手记(四)

Apache Mina使用手记(四) 分类: JAVA 2009-03-13 20:46 13809人阅读 评论(19) 收藏 举报 minaapacheexceptionsessionstringbyte 上一篇中,我们介绍了如何在mina中编写自己的日志过滤器,这一篇我们自己实现一个编解器. 实际应用当,很多应用系统应用的都不是标准的web service或XML等,比如象中国移动/联通/电信的短信网关程序,都有自己不同的协议实现,并且都是基于TCP/IP的字节流.Mina自带的编解码器实现

Apache Mina使用手记(一)

Apache Mina使用手记(一) 分类: JAVA 2009-03-11 20:17 6069人阅读 评论(5) 收藏 举报 minaapacheslf4jloggingjavavb 1.Apache Mina是一个高性能的基础网络构架平台,构建在java NIO的基础上 2.Mina使用了SLF4J做为日志记录器,全称Simple Logging Facade for Java,它是一个日志门面,只负责为客户端提供应用接口,实际的日志记录由Log4j/JUL等日志记录器实现.如下图所示:

Apache Mina使用手记(二)

Apache Mina使用手记(二) 分类: JAVA 2009-03-11 21:28 8707人阅读 评论(4) 收藏 举报 minaapachelog4jexceptionslf4jmicrosoft  Mina主要是作为服务器端底层框架来实现数据处理,它的实现很简单,如下例所示: package com.gftech.mytool.mina; import java.io.IOException; import java.net.InetSocketAddress; import jav

org.apache.mina.core.RuntimeIoException: Failed to get the session

问题描述 我用线程起了一个mina服务端,客户端连接服务端mina时报错.请大神赐教.org.apache.mina.core.RuntimeIoException:Failedtogetthesession 解决方案 解决方案二:补充Causedby:java.net.ConnectException:Connectionrefused解决方案三:查查看连接不上了.解决方案四:有没有人解决啊解决方案五:如果我这边Web服务器用IoConnect连接别人的服务器,是不是别人也要用Mina的IoA

使用 Apache MINA 2 开发网络应用

Apache MINA 2 是一个开发高性能和高可伸缩性网络应用程序的网络应用框架.它提供了一个抽象的事件驱动的异步 API,可以使用 TCP/IP.UDP/IP.串口和虚拟机内部的管道等传输方式.Apache MINA 2 可以作为开发网络应用程序的一个良好基础.下面将首先简单介绍一下 Apache MINA 2. Apache MINA 2 介绍 Apache MINA 是 Apache 基金会的一个开源项目,目前最新的版本是 2.0.0-RC1.本文中使用的版本是 2.0.0-M6.下面首

Apache Mina通信框架架构与应用

Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于 TCP/IP.UDP/IP协议栈的通信框架(当然,也可以提供 JAVA 对象的序列化服务.虚拟机管道通信服务等),Mina 可以帮助我们快速开发高性能.高扩展性的网络通信应用,Mina 提供了事件驱动.异步(Mina 的异步 IO 默认使用的是 JAVA NIO 作为底层支持)操作的编程模型.从官网文档"MINA based Application Architecture"中可以看到Mina作为一

【APACHE MINA2.0开发之一】搭建APACHE MINA框架并实现SERVER与CLIENT端的简单消息传递!

本站文章均为 李华明Himi 原创,转载务必在明显处注明:  转载自[黑米GameDev街区] 原文链接: http://www.himigame.com/apache-mina/831.html Hibernate系列学习阶段到此结束了,那么紧接着进入Apache Mina的开发学习,很多童鞋在微薄和QQ中疑问Himi为什么突然脱离游戏开发了,嘿嘿,其实可能更多的童鞋已经看出来了,Himi在偏向服务器Server端开发了,Hibernate.MySQL等都是为了Server端Mina开发而做的

Apache MINA (3) NioSocketAcceptor初始化

上一篇博客Apache MINA (2) Hello World! 以一个例子实现了mina客户端和服务端的通讯,现在通过源码来了解建立连接和通讯的过程(基于tcp/ip的实现). 服务端通过创建一个NioSocketAcceptor来接受请求,客户端通过创建NioSocketConnector来连接服务端并发送请求,从整体的体系结构来看二者的关系. IoService是对于服务器端接受连接和客户端发起连接两类行为的一个抽象.IoServer用来执行真正的 I/O 操作,以及管理 I/O 会话.

解决 Missing artifact org.apache.mina:mina-core:bundle:2.0.9

Maven 项目中引用了 MINA 的依赖,包如下错误: Missing artifact org.apache.mina:mina-core:bundle:2.0.9 依赖 项目引入的 MINA 依赖如下: <dependency> <groupId>org.apache.mina</groupId> <artifactId>mina-core</artifactId> <version>${version.mina}</ve