用Java读写memcache的两种方法

        Memcache服务器启动之后,可以采用Python,java,c,c#等多种语言对其进行读写,每种语言都在其各自的基础上创建有memcache客户端读写API。本文章主要介绍两种用java读写memcache的方法:


方法一:用MemCache读写memcache的JAVA 实例:

package mytest;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;


public class MemcacheStore {
	protected MemCachedClient mcc;
	
	static{
		String[] servers = {"your ip address"};
		Integer[] weights = {1};
		SockIOPool pool = SockIOPool.getInstance();
	
		pool.setServers(servers);
		pool.setWeights(weights);
		
		pool.setNagle(false);
		pool.setSocketTO(3000);
		pool.setSocketConnectTO(0);
		
		pool.initialize();
	}
	public MemcacheStore(){
		mcc = new MemCachedClient();
	}
	
	public boolean storeChannel(String channelId){
		mcc.set(channelId, "exist");
		return true;
	}
	
	public boolean removeChannel(String channelId){
		mcc.set(channelId, "no exist");
		return true;
	}
	
	public static void main(String[] arg){
		MemcacheStore mem = new MemcacheStore();
		mem.storeChannel("1");
	}
}

其中,我们可以设置多个memcache服务器组成的cluster结构,并且有效地设置各个服务器上的权重:

       
        String[] servers =
                {
                        "10.15.0.215:46697",
                        "10.15.0.214:46697",

                };

        // 设置服务器权重
        Integer[] weights = {3, 2};

get和set函数可以用于读写memcache。


方法二:用xmemcached读写memcache:

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;

public class Xmemcached {
	public static void main(String[] args){
	    try {
		MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("your ip and port"));
		MemcachedClient memcachedClient = builder.build();
	        memcachedClient.set( "hello" , 0, "Hello,xmemcached" );
	        String value = memcachedClient.get( "hello" );
	        System.out.println( "hello=" + value);
	        //memcachedClient.delete( "hello" );
	        value = memcachedClient.get( "hello" );
	    } catch (MemcachedException e) {
	        System.err.println( "MemcachedClient operation fail" );
	        e.printStackTrace();
	    } catch (TimeoutException e) {
	        System.err.println( "MemcachedClient operation timeout" );
	        e.printStackTrace();
	    } catch (InterruptedException e) {
	        // ignore
	    } catch (IOException e) {
	    	// ignore
	    }
//	    try {
////	    	memcachedClient.shutdown();
//	    } catch (IOException e) {
//	        System. err .println( "Shutdown MemcachedClient fail" );
//	        e.printStackTrace();
//	    }
	}

}


你可能感兴趣的:(java,String,服务器,Integer,Class,语言)