Skip to content

Instantly share code, notes, and snippets.

@Karry
Last active December 15, 2015 16:49
Show Gist options
  • Save Karry/5291694 to your computer and use it in GitHub Desktop.
Save Karry/5291694 to your computer and use it in GitHub Desktop.
Http chunk cache is designed for sharing part of http response (on top of JBoss Netty) that is identical for many clients. Response have to be send as http/1.1 chunks. As key is used Google proto buffer, but it is simple to rewrite to something different.
/**
* <pre>
* Copyright (c) 2013, AVAST Software a.s.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the AVAST Software a.s. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* </pre>
*
*/
import com.google.protobuf.MessageLite;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Map;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.util.CharsetUtil;
import org.jboss.netty.util.internal.ConcurrentWeakKeyHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Http chunk cache is designed for sharing part of http response that is
* identical for many clients. Response have to be send as http/1.1 chunks. As
* key is used Google proto buffer, but it is simple to rewrite to something
* different.
*
* @author karry
*/
public class HttpChunkCache {
/**
* Carriage return
*/
static final byte CR = 13;
/**
* Line feed character
*/
static final byte LF = 10;
/**
* carriage return line feed
*/
static final byte[] CRLF = new byte[]{CR, LF};
private static final Logger LOGGER = LoggerFactory.getLogger(HttpChunkCache.class);
private final Map<MessageLite, ByteBuffer> weakMap = new ConcurrentWeakKeyHashMap<MessageLite, ByteBuffer>();
/**
* Create new ByteBuffer with shared direct memory filled from bytes of
* message and packaged into http chunk.
*/
public ByteBuffer get(MessageLite message) {
ByteBuffer directByteBuffer = weakMap.get(message);
if (directByteBuffer != null)
return directByteBuffer.slice(); // create clone with shared memory area
byte[] contentBytes = message.toByteArray();
int contentLength = contentBytes.length;
// create http chunk (this code is copied from org.jboss.netty.handler.codec.http.HttpMessageEncoder)
ChannelBuffer chunkBuffer = ChannelBuffers.wrappedBuffer(
ChannelBuffers.copiedBuffer(
Integer.toHexString(contentLength),
CharsetUtil.US_ASCII),
ChannelBuffers.wrappedBuffer(CRLF),
ChannelBuffers.wrappedBuffer(contentBytes),
ChannelBuffers.wrappedBuffer(CRLF));
// copy buffer to direct buffer - it can be propagate to kernel without copy
int capacity = chunkBuffer.readableBytes();
directByteBuffer = ByteBuffer.allocateDirect(capacity).order(ByteOrder.BIG_ENDIAN);
chunkBuffer.readBytes(directByteBuffer);
directByteBuffer.flip(); // rewind to begining
LOGGER.debug("put into cache " + message.hashCode() + " " + (((double) directByteBuffer.capacity()) / 1024d) + " KiB");
weakMap.put(message, directByteBuffer);
return directByteBuffer.slice(); // create clone with shared memory area
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment