java memcache

package com.my.util;


import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
import com.my.prop.CenterProp;




public class MemCachedClientUtil {


private static MemCachedClient mc;


private static SockIOPool initedPool;


static {


String serverlist = CenterProp.memcacheServer;
String[] servers = serverlist.split(",");


initedPool = SockIOPool.getInstance();


initedPool.setServers(servers);
initedPool.setFailover(false);
initedPool.setInitConn(20);
initedPool.setMinConn(300);
initedPool.setMaxConn(30000);
initedPool.setMaintSleep(3000);
initedPool.setNagle(false);
initedPool.setSocketTO(30000);
initedPool.setAliveCheck(true);
initedPool.initialize();


mc = new MemCachedClient();
}


public static SockIOPool getPool() {
return initedPool;
}


public static MemCachedClient getClient() {
return mc;
}

}


由于公司b2b项目登录有问题,老是登录不上,后来查到可能由于缓存连接数太多的问题

大多数人new MemCachedClient()都是到处new,不过这个也不是很有问题的,但是如果用户量较大多次创建新的对象还是会耗一些时间和内存的,

所以同事想着把此类改成单例的。

查看源码中的MemcachedClient

package com.meetup.memcached


public class MemcachedClient {


public Object get( String key, Integer hashCode, boolean asString ) {


if ( key == null ) {
log.error( "key is null for get()" );
return null;
}


try {
key = sanitizeKey( key );
}
catch ( UnsupportedEncodingException e ) {


// if we have an errorHandler, use its hook
if ( errorHandler != null )
errorHandler.handleErrorOnGet( this, e, key );


log.error( "failed to sanitize your key!", e );
return null;
}


// get SockIO obj using cache key
SockIOPool.SockIO sock = pool.getSock( key, hashCode ); //拿到sock通信连接   
   if ( sock == null ) {
if ( errorHandler != null )
errorHandler.handleErrorOnGet( this, new IOException( "no socket to server available" ), key );
return null;
}


try {
String cmd = "get " + key + "\r\n";


if ( log.isDebugEnabled() )
log.debug("++++ memcache get command: " + cmd);

sock.write( cmd.getBytes() );
sock.flush();


// ready object
Object o = null;


while ( true ) {
String line = sock.readLine();


if ( log.isDebugEnabled() )
log.debug( "++++ line: " + line );


if ( line.startsWith( VALUE ) ) {
String[] info = line.split(" ");
int flag      = Integer.parseInt( info[2] );
int length    = Integer.parseInt( info[3] );


if ( log.isDebugEnabled() ) {
log.debug( "++++ key: " + key );
log.debug( "++++ flags: " + flag );
log.debug( "++++ length: " + length );
}

// read obj into buffer
byte[] buf = new byte[length];
sock.read( buf );
sock.clearEOL();


if ( (flag & F_COMPRESSED) == F_COMPRESSED ) {
try {
// read the input stream, and write to a byte array output stream since
// we have to read into a byte array, but we don't know how large it
// will need to be, and we don't want to resize it a bunch
GZIPInputStream gzi = new GZIPInputStream( new ByteArrayInputStream( buf ) );
ByteArrayOutputStream bos = new ByteArrayOutputStream( buf.length );

int count;
byte[] tmp = new byte[2048];
while ( (count = gzi.read(tmp)) != -1 ) {
bos.write( tmp, 0, count );
}


// store uncompressed back to buffer
buf = bos.toByteArray();
gzi.close();
}
catch ( IOException e ) {


// if we have an errorHandler, use its hook
if ( errorHandler != null )
errorHandler.handleErrorOnGet( this, e, key );


log.error( "++++ IOException thrown while trying to uncompress input stream for key: " + key + " -- " + e.getMessage() );
throw new NestedIOException( "++++ IOException thrown while trying to uncompress input stream for key: " + key, e );
}
}


// we can only take out serialized objects
if ( ( flag & F_SERIALIZED ) != F_SERIALIZED ) {
if ( primitiveAsString || asString ) {
// pulling out string value
if ( log.isInfoEnabled() )
log.info( "++++ retrieving object and stuffing into a string." );
o = new String( buf, defaultEncoding );
}
else {
// decoding object
try {
o = NativeHandler.decode( buf, flag );    
}
catch ( Exception e ) {


// if we have an errorHandler, use its hook
if ( errorHandler != null )
errorHandler.handleErrorOnGet( this, e, key );


log.error( "++++ Exception thrown while trying to deserialize for key: " + key, e );
throw new NestedIOException( e );
}
}
}
else {
// deserialize if the data is serialized
ContextObjectInputStream ois =
new ContextObjectInputStream( new ByteArrayInputStream( buf ), classLoader );
try {
o = ois.readObject();
if ( log.isInfoEnabled() )
log.info( "++++ deserializing " + o.getClass() );
}
catch ( Exception e ) {
if ( errorHandler != null )
errorHandler.handleErrorOnGet( this, e, key );


o = null;
log.error( "++++ Exception thrown while trying to deserialize for key: " + key + " -- " + e.getMessage() );
}
}
}
else if ( END.equals( line ) ) {
if ( log.isDebugEnabled() )
log.debug( "++++ finished reading from cache server" );
break;
}
}

sock.close();
sock = null;
return o;
   }
catch ( IOException e ) {


// if we have an errorHandler, use its hook
if ( errorHandler != null )
errorHandler.handleErrorOnGet( this, e, key );


// exception thrown
log.error( "++++ exception thrown while trying to get object from cache for key: " + key + " -- " + e.getMessage() );


try {
sock.trueClose();
}
catch ( IOException ioe ) {
log.error( "++++ failed to close socket : " + sock.toString() );
}
sock = null;
   }


if ( sock != null )
sock.close();


return null;
}


从上面源码可看出 MemCachedClient()是多线程的,所以单个 MemCachedClient()足以满足要求

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值