国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > 服务器 > xmemcached 动态增加节点

xmemcached 动态增加节点

来源:程序员人生   发布时间:2015-01-26 08:51:21 阅读次数:3188次

1.介绍

支持所有的基于文本的协议和2进制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认证2进制协议有效的。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方法来增加或减少计数器有1个计数器xmemcached封装增加/减少的方法你可使用计数器就像AtomicLong


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

8. 2进制协议。

 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();         } }




生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生