apache mina 学习(七)-----IoFilter

IoFilter是mina中一个非常重要的设计,它可以过滤IoServiceIoHandler之间的所有的io流,经常会用到的过滤器:

1、日志过滤器LoggingFilter

2、协议编码过滤器ProtocolCodecFilter(可以把输入的bytebuffer转换为pojo)

3、压缩过滤器CompressionFilter用于压缩数据

4、sslFilter用于支持ssl

已经存在的过滤器及实现类:

Filter class Description
Blacklist BlacklistFilter Blocks connections from blacklisted remote addresses
Buffered Write BufferedWriteFilter Buffers outgoing requests like the BufferedOutputStream does
Compression CompressionFilter
ConnectionThrottle ConnectionThrottleFilter
ErrorGenerating ErrorGeneratingFilter
Executor ExecutorFilter
FileRegionWrite FileRegionWriteFilter
KeepAlive KeepAliveFilter
Logging LoggingFilter Logs event messages, like MessageReceived, MessageSent, SessionOpened, ...
MDC Injection MdcInjectionFilter Inject key IoSession properties into the MDC
Noop NoopFilter A filter that does nothing. Useful for tests.
Profiler ProfilerTimerFilter Profile event messages, like MessageReceived, MessageSent, SessionOpened, ...
ProtocolCodec ProtocolCodecFilter A filter in charge of encoding and decoding messages
Proxy ProxyFilter
Reference counting ReferenceCountingFilter Keeps track of the number of usages of this filter
RequestResponse RequestResponseFilter
SessionAttributeInitializing SessionAttributeInitializingFilter
StreamWrite StreamWriteFilter
SslFilter SslFilter
WriteRequest WriteRequestFilter

如果想实现自己的Filter只需集成

IoFilterAdapter抽象类即可。
下面是一个字节数组过滤成字符的Filter例子:
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest request) {
    String m = (String) request.getMessage();
    ByteBuffer newBuffer = new MyByteBuffer(m, ByteBuffer.wrap(m.getBytes());

    nextFilter.filterWrite(
            session, new WriteRequest(newBuffer, request.getFuture(), request.getDestination()));
}

public void messageSent(NextFilter nextFilter, IoSession session, Object message) {
    if (message instanceof MyByteBuffer) {
        nextFilter.messageSent(session, ((MyByteBuffer) message).originalValue);
    } else {
        nextFilter.messageSent(session, message);
    }
}

private static class MyByteBuffer extends ByteBufferProxy {
    private final Object originalValue;
    private MyByteBuffer(Object originalValue, ByteBuffer encodedValue) {
        super(encodedValue);
        this.originalValue = originalValue;
    }
}

 


你可能感兴趣的:(apache)