Google
 
Web unafbapune.blogspot.com

Wednesday, September 13, 2006

 

WriteThottleFilter in Mina

I was wondering if there is an easy way in Mina 0.8.2 to control the rate of physical network write operations to not exceed a specific number of messages.

For example, can I say for a particular socket connection session Mina should write physically no more than 3 messages per second ? Message here means the argument that get passed to ProtocolSession.write(Object).

AFAIK the ProtocolSession.write() is a logical asyn operation, and Mina therefore reserves the right to buffer it underneath. If so, controlling the rate of session.write() cannot be relied upon to control the rate of physical messages that get sent down the wire.

So I posted the question to the Mina developer forum, and here is the reply by Trustin Lee:
"You are correct, but you can make session.write() a blocking operation by inserting a filter which limits the write rate. Please implement your filter's filterWrite() to throttle the write request.

BTW this idea is nice. Could you please create a JIRA issue for us so we can resolve it someday and you can switch over to our version of write rate limiting filter? Otherwise you could contribute! ;)"

It turns out the implementation can be quite simple:
...
SocketConnector socketConnector = new SocketConnector();
socketConnector.getFilterChain()
.addLast("writeThrottleFilter",
new WriteThrottleFilter(333));
...

public class WriteThrottleFilter extends IoFilterAdapter
{
/** Delay in milli-seconds between writes. */
private final long delayMillis;

public WriteThrottleFilter(long delayMillis) {
this.delayMillis = delayMillis;
}

@Override
public synchronized void filterWrite(NextFilter nextFilter,
IoSession session, ByteBuffer buf, Object marker)
throws InterruptedException
{
nextFilter.filterWrite( session, buf, marker );
Thread.sleep(delayMillis);
}
}
Thanks to Trustin Lee, this class will be included in the Mina 1.0 release! More details here.

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?