码迷,mamicode.com
首页 > 系统相关 > 详细

xmemcached 动态增加节点

时间:2015-01-21 15:13:22      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:memcached   client   缓存   分布式缓存   

1.介绍

支持所有的基于文本的协议和二进制memcached的基础协议,目前包括获取/设置获取添加删除添加替换prependCAS得到/得到增加降低flush_all统计等。

2.依赖

如果是maven工程

<dependency>
       <groupId>com.googlecode.xmemcached</groupId>
       <artifactId>xmemcached</artifactId>
       <version>${version}</version>
  </dependency>
3.例子

MemcachedClient client=new XMemcachedClient("host",11211);

//store a value for one hour(synchronously).
client.set("key",3600,someObject);
//Retrieve a value.(synchronously).
Object someObject=client.get("key");
//Retrieve a value.(synchronously),operation timeout two seconds.
someObject=client.get("key",2000);

//Touch cache item ,update it‘s expire time to 10 seconds.
boolean success=client.touch("key",10);

//delete value
client.delete("key");
4.Weighted Server(节点权重)

设置 localhost:12000 的权重为1,设置 localhost:12001 的权重为3.

 MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:12000 localhost:12001"),new int[]{1,3});
 MemcachedClient memcachedClient=builder.build();

可以通过jmx动态改变权重

   public interface XMemcachedClientMBean{
             ....
         /**
         * Set a memcached server‘s weight
         * 
         * @param server
         * @param weight
         */
        public void setServerWeight(String server, int weight);
   }
5. 获取所有key
MemcachedClient client=...
KeyIterator it=client.getKeyIterator(AddrUtil.getOneAddress("localhost:11211"));
while(it.hasNext())
{
   String key=it.next();
}

6.SASL认证

Memcached客户端1.4.3支持SASL认证二进制协议有效的。xmemcached 1.2.5支持此功能如果memcached服务器启用SASL使用CRAM-MD5或普通的机制设置用户名为“cacheuser”和密码为“123456”那么你可以使用xmemcached这样

 MemcachedClientBuilder builder = new XMemcachedClientBuilder(
                                        AddrUtil.getAddresses(server));
   builder.addAuthInfo(AddrUtil.getOneAddress(server), AuthInfo
                                        .typical("cacheuser", "password"));
    // Must use binary protocol
    builder.setCommandFactory(new BinaryCommandFactory());
    MemcachedClient client=builder.build();


7.使用计数器来增加/减少

您可以使用增加/减少memcachedclient方法来增加或减少计数器有一个计数器xmemcached封装增加/减少的方法你可以使用计数器就像AtomicLong


Counter counter=client.getCounter("counter",0);
counter.incrementAndGet();
counter.decrementAndGet();
counter.addAndGet(-10);

8. 二进制协议。

 MemcachedClientBuilder builder = new    XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:12000 localhost:12001"),new int[]{1,3});
 builder.setCommandFactory(new BinaryCommandFactory());//use binary protocol 
 MemcachedClient memcachedClient=builder.build();
9.Kestrel
MemcachedClientBuilder builder = new    XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:12000 localhost:12001"),new int[]{1,3});
   builder.setCommandFactory(new KestrelCommandFactory());
   MemcachedClient memcachedClient=builder.build();
 // 存储字符串

 client.setPrimitiveAsString(true);

10.动态增加节点

MemcachedClient client=new XMemcachedClient(AddrUtil.getAddresses("server1:11211 server2:11211"));
   //Add two new memcached nodes
   client.addServer("server3:11211 server4:11211");
   //Remove memcached servers
   client.removeServer("server1:11211 server2:11211");

11.设置连接池

 MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:12000"));

 builder.setConnectionPoolSize(5); //set connection pool size to five

12 Cas操作

 class CASThread extends Thread {
        static final class IncrmentOperation implements CASOperation<Integer> {
                /*
                 *Max repeat times.if repeat times is great than this value,
                 *xmemcached will throw a TimeoutException.
                 */
                @Override
                public int getMaxTries() {
                        return Integer.MAX_VALUE; 
                }

                //increase current value                
                @Override
                public Integer getNewValue(long currentCAS, Integer currentValue) {
                        return currentValue + 1; // current value + 1
                }
        }

        private XMemcachedClient mc;
        private CountDownLatch cd;

        public CASThread(XMemcachedClient mc, CountDownLatch cdl) {
                super();
                this.mc = mc;
                this.cd = cdl;

        }

        public void run() {
                try {
                        //do the cas operation
                        if (mc.cas("a", 0, new IncrmentOperation()))
                                this.cd.countDown();
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}

public class CASTest {

        public static void main(String[] args) throws Exception {
                if (args.length < 2) {
                        System.err.println("Usage:java CASTest [threadNum] [server]");
                    System.exit(1);
                }
                //threads num
                int NUM = Integer.parseInt(args[0]);
                XMemcachedClient mc = new XMemcachedClient(AddrUtil.getAddresses(args[1]));
                //initial value is 0
                mc.set("a", 0, 0);
                CountDownLatch cdl = new CountDownLatch(NUM);
                long start = System.currentTimeMillis();
                //start NUM threads to increment the value
                for (int i = 0; i < NUM; i++)
                        new CASThread(mc, cdl).start();

                cdl.await();
                System.out.println("test cas,timed:"
                                + (System.currentTimeMillis() - start));
                System.out.println("result=" + mc.get("a"));
                mc.shutdown();
        }
}




xmemcached 动态增加节点

标签:memcached   client   缓存   分布式缓存   

原文地址:http://blog.csdn.net/liuzhiquan_1025/article/details/42967701

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!