XMemcached使用示例

本文介绍了XMemcached客户端的基本用法,包括连接配置、基本操作如set/get/delete,以及高级特性如CAS更新、计数器操作等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Memcached 是一个高性能的分布式内存对象的key-value缓存系统,用于动态Web应用以减轻数据库负载,现在也有很多人将它作为内存式数据库在使用,memcached通过它的自定义协议与客户端交互,而XMemcached就是它的一个java客户端实现。

 

XMemcached使用示例(本示例基于xmemcached-1.3.8.jar),总结一个,如下:

Java代码   收藏代码
  1. package com.wujintao.memcached;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.concurrent.TimeoutException;  
  5.   
  6. import net.rubyeye.xmemcached.Counter;  
  7. import net.rubyeye.xmemcached.GetsResponse;  
  8. import net.rubyeye.xmemcached.MemcachedClient;  
  9. import net.rubyeye.xmemcached.MemcachedClientBuilder;  
  10. import net.rubyeye.xmemcached.XMemcachedClientBuilder;  
  11. import net.rubyeye.xmemcached.auth.AuthInfo;  
  12. import net.rubyeye.xmemcached.command.BinaryCommandFactory;  
  13. import net.rubyeye.xmemcached.exception.MemcachedException;  
  14. import net.rubyeye.xmemcached.transcoders.StringTranscoder;  
  15. import net.rubyeye.xmemcached.utils.AddrUtil;  
  16.   
  17. import org.junit.Test;  
  18.   
  19. import com.wujintao.redis.util.MD5Util;  
  20.   
  21. public class TestCase {  
  22.     @Test  
  23.     public void test1() throws IOException {  
  24.         MemcachedClientBuilder builder = new XMemcachedClientBuilder(  
  25.                 AddrUtil.getAddresses("localhost:11211"));  
  26.         // AddrUtil.getAddresses("server1:11211 server2:11211")  
  27.                // 宕机报警    
  28.                builder.setFailureMode(true);    
  29.               // 使用二进制文件    
  30.                builder.setCommandFactory(new BinaryCommandFactory());  
  31.             /**  
  32.              * 设置连接池大小,即客户端个数  
  33.              * In a high concurrent enviroment,you may want to pool memcached clients.  
  34.              * But a xmemcached client has to start a reactor thread and some thread pools,  
  35.              * if you create too many clients,the cost is very large.   
  36.              * Xmemcached supports connection pool instreadof client pool.  
  37.              * you can create more connections to one or more memcached servers,  
  38.              * and these connections share the same reactor and thread pools,  
  39.              * it will reduce the cost of system.  
  40.              *  默认的pool size是1。设置这一数值不一定能提高性能,请依据你的项目的测试结果为准。初步的测试表明只有在大并发下才有提升。  
  41.              *  设置连接池的一个不良后果就是,同一个memcached的连接之间的数据更新并非同步的  
  42.              *  因此你的应用需要自己保证数据更新的原子性(采用CAS或者数据之间毫无关联)。  
  43.              */    
  44.                 builder.setConnectionPoolSize(10);    
  45.         MemcachedClient client = builder.build();  
  46.         try {  
  47.             /** 
  48.              * 第一个是存储的key名称, 
  49.              * 第二个是expire时间(单位秒),超过这个时间,memcached将这个数据替换出去,0表示永久存储(默认是一个月) 
  50.              * 第三个参数就是实际存储的数据 
  51.              */  
  52.             client.set("hello"0"Hello,xmemcached");  
  53.             String value = client.get("hello");  
  54.             System.out.println("hello=" + value);  
  55.             client.delete("hello");  
  56.             value = client.get("hello");  
  57.             System.out.println("hello=" + value);  
  58.   
  59.             // value=client.get(“hello”,3000);  
  60.   
  61.             /** 
  62.              * Memcached是通过cas协议实现原子更新,所谓原子更新就是compare and set, 
  63.              * 原理类似乐观锁,每次请求存储某个数据同时要附带一个cas值, memcached比对这个cas值与当前存储数据的cas值是否相等, 
  64.              * 如果相等就让新的数据覆盖老的数据,如果不相等就认为更新失败, 这在并发环境下特别有用 
  65.              */  
  66.             GetsResponse<Integer> result = client.gets("a");  
  67.             long cas = result.getCas();  
  68.             // 尝试将a的值更新为2  
  69.             if (!client.cas("a"02, cas)) {  
  70.                 System.err.println("cas error");  
  71.             }  
  72.         } catch (MemcachedException e) {  
  73.             System.err.println("MemcachedClient operation fail");  
  74.             e.printStackTrace();  
  75.         } catch (TimeoutException e) {  
  76.             System.err.println("MemcachedClient operation timeout");  
  77.             e.printStackTrace();  
  78.         } catch (InterruptedException e) {  
  79.             // ignore  
  80.         }  
  81.         try {  
  82.             // close memcached client  
  83.             client.shutdown();  
  84.         } catch (IOException e) {  
  85.             System.err.println("Shutdown MemcachedClient fail");  
  86.             e.printStackTrace();  
  87.         }  
  88.   
  89.     }  
  90.   
  91.     @Test  
  92.     public void test2() throws TimeoutException, InterruptedException,  
  93.             MemcachedException, IOException {  
  94.         MemcachedClientBuilder builder = new XMemcachedClientBuilder(  
  95.                 AddrUtil.getAddresses("localhost:11211"));  
  96.         MemcachedClient client = builder.build();  
  97.         client.flushAll();  
  98.         if (!client.set("hello"0"world")) {  
  99.             System.err.println("set error");  
  100.         }  
  101.         if (client.add("hello"0"dennis")) {  
  102.             System.err.println("Add error,key is existed");  
  103.         }  
  104.         if (!client.replace("hello"0"dennis")) {  
  105.             System.err.println("replace error");  
  106.         }  
  107.         client.append("hello"" good");  
  108.         client.prepend("hello""hello ");  
  109.         String name = client.get("hello"new StringTranscoder());  
  110.         System.out.println(name);  
  111.   
  112.         /** 
  113.          * 而删除数据则是通过deleteWithNoReply方法,这个方法删除数据并且告诉memcached 
  114.          * 不用返回应答,因此这个方法不会等待应答直接返回,特别适合于批量处理 
  115.          */  
  116.         client.deleteWithNoReply("hello");  
  117.     }  
  118.   
  119.     @Test  
  120.     public void incrDecr() throws IOException, TimeoutException,  
  121.             InterruptedException, MemcachedException {  
  122.         MemcachedClientBuilder builder = new XMemcachedClientBuilder(  
  123.                 AddrUtil.getAddresses("localhost:11211"));  
  124.         MemcachedClient client = builder.build();  
  125.         /** 
  126.          * 第一个参数指定递增的key名称, 第二个参数指定递增的幅度大小, 第三个参数指定当key不存在的情况下的初始值。 
  127.          * 两个参数的重载方法省略了第三个参数,默认指定为0。 
  128.          */  
  129.         assert (1 == client.incr("a"51));  
  130.         assert (6 == client.incr("a"5));  
  131.         assert (10 == client.incr("a"4));  
  132.         assert (9 == client.decr("a"1));  
  133.         assert (7 == client.decr("a"2));  
  134.     }  
  135.   
  136.     @Test  
  137.     public void counter() throws Exception {  
  138.         MemcachedClientBuilder builder = new XMemcachedClientBuilder(  
  139.                 AddrUtil.getAddresses("localhost:11211"));  
  140.         MemcachedClient client = builder.build();  
  141.         Counter counter = client.getCounter("counter"0);  
  142.         counter.incrementAndGet();  
  143.         counter.decrementAndGet();  
  144.         counter.addAndGet(-10);  
  145.     }  
  146.   
  147.     public void auth() throws Exception {  
  148.         MemcachedClientBuilder builder = new XMemcachedClientBuilder(  
  149.                 AddrUtil.getAddresses("localhost:11211"));  
  150.         builder.addAuthInfo(AddrUtil.getOneAddress("localhost:11211"),  
  151.                 AuthInfo.typical("cacheuser""123456"));  
  152.         // Must use binary protocol  
  153.         builder.setCommandFactory(new BinaryCommandFactory());  
  154.         MemcachedClient client = builder.build();  
  155.     }  
  156.   
  157.     public void nioPool() throws Exception {  
  158.         MemcachedClientBuilder builder = new XMemcachedClientBuilder(  
  159.                 AddrUtil.getAddresses("localhost:11211"));  
  160.         builder.setConnectionPoolSize(5);  
  161.     }  
  162.   
  163.       
  164.     /** 
  165.      *这里应该安装kestrel消息服务器,才能使用如下API生效 
  166.      * @throws IOException 
  167.      * @throws MemcachedException  
  168.      * @throws InterruptedException  
  169.      * @throws TimeoutException  
  170.      */  
  171.     @Test  
  172.     public void testGet() throws IOException, TimeoutException, InterruptedException, MemcachedException{  
  173.         MemcachedClientBuilder builder = new XMemcachedClientBuilder(  
  174.                 AddrUtil.getAddresses("localhost:11212"));  
  175.         MemcachedClient client = builder.build();  
  176.         String value = client.get("1");  
  177.         System.out.println("hello=" + value);  
  178.     }  
  179.       
  180.       
  181.     @Test  
  182.     public void testGet2() throws IOException, TimeoutException, InterruptedException, MemcachedException{  
  183.         MemcachedClientBuilder builder = new XMemcachedClientBuilder(  
  184.                 AddrUtil.getAddresses("localhost:11212"));  
  185.         MemcachedClient client = builder.build();  
  186.         String value = client.get("srp_"+MD5Util.MD5("3rdsearch_周杰伦"));  
  187.         System.out.println(value);  
  188.     }  
  189. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值