XMemcached使用示例--转
生活随笔
收集整理的這篇文章主要介紹了
XMemcached使用示例--转
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Memcached 是一個高性能的分布式內存對象的key-value緩存系統,用于動態Web應用以減輕數據庫負載,現在也有很多人將它作為內存式數據庫在使用,memcached通過它的自定義協議與客戶端交互,而XMemcached就是它的一個java客戶端實現。
XMemcached使用示例(本示例基于xmemcached-1.3.8.jar),總結一個,如下:
?
package com.wujintao.memcached;import java.io.IOException; import java.util.concurrent.TimeoutException;import net.rubyeye.xmemcached.Counter; import net.rubyeye.xmemcached.GetsResponse; import net.rubyeye.xmemcached.MemcachedClient; import net.rubyeye.xmemcached.MemcachedClientBuilder; import net.rubyeye.xmemcached.XMemcachedClientBuilder; import net.rubyeye.xmemcached.auth.AuthInfo; import net.rubyeye.xmemcached.command.BinaryCommandFactory; import net.rubyeye.xmemcached.exception.MemcachedException; import net.rubyeye.xmemcached.transcoders.StringTranscoder; import net.rubyeye.xmemcached.utils.AddrUtil;import org.junit.Test;import com.wujintao.redis.util.MD5Util;public class TestCase {@Testpublic void test1() throws IOException {MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));// AddrUtil.getAddresses("server1:11211 server2:11211")// 宕機報警 builder.setFailureMode(true); // 使用二進制文件 builder.setCommandFactory(new BinaryCommandFactory());/** * 設置連接池大小,即客戶端個數 * In a high concurrent enviroment,you may want to pool memcached clients. * But a xmemcached client has to start a reactor thread and some thread pools, * if you create too many clients,the cost is very large. * Xmemcached supports connection pool instreadof client pool. * you can create more connections to one or more memcached servers, * and these connections share the same reactor and thread pools, * it will reduce the cost of system. * 默認的pool size是1。設置這一數值不一定能提高性能,請依據你的項目的測試結果為準。初步的測試表明只有在大并發下才有提升。 * 設置連接池的一個不良后果就是,同一個memcached的連接之間的數據更新并非同步的 * 因此你的應用需要自己保證數據更新的原子性(采用CAS或者數據之間毫無關聯)。 */ builder.setConnectionPoolSize(10); MemcachedClient client = builder.build();try {/*** 第一個是存儲的key名稱,* 第二個是expire時間(單位秒),超過這個時間,memcached將這個數據替換出去,0表示永久存儲(默認是一個月)* 第三個參數就是實際存儲的數據*/client.set("hello", 0, "Hello,xmemcached");String value = client.get("hello");System.out.println("hello=" + value);client.delete("hello");value = client.get("hello");System.out.println("hello=" + value);// value=client.get(“hello”,3000);/*** Memcached是通過cas協議實現原子更新,所謂原子更新就是compare and set,* 原理類似樂觀鎖,每次請求存儲某個數據同時要附帶一個cas值, memcached比對這個cas值與當前存儲數據的cas值是否相等,* 如果相等就讓新的數據覆蓋老的數據,如果不相等就認為更新失敗, 這在并發環境下特別有用*/GetsResponse<Integer> result = client.gets("a");long cas = result.getCas();// 嘗試將a的值更新為2if (!client.cas("a", 0, 2, cas)) {System.err.println("cas error");}} 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 }try {// close memcached client client.shutdown();} catch (IOException e) {System.err.println("Shutdown MemcachedClient fail");e.printStackTrace();}}@Testpublic void test2() throws TimeoutException, InterruptedException,MemcachedException, IOException {MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));MemcachedClient client = builder.build();client.flushAll();if (!client.set("hello", 0, "world")) {System.err.println("set error");}if (client.add("hello", 0, "dennis")) {System.err.println("Add error,key is existed");}if (!client.replace("hello", 0, "dennis")) {System.err.println("replace error");}client.append("hello", " good");client.prepend("hello", "hello ");String name = client.get("hello", new StringTranscoder());System.out.println(name);/*** 而刪除數據則是通過deleteWithNoReply方法,這個方法刪除數據并且告訴memcached* 不用返回應答,因此這個方法不會等待應答直接返回,特別適合于批量處理*/client.deleteWithNoReply("hello");}@Testpublic void incrDecr() throws IOException, TimeoutException,InterruptedException, MemcachedException {MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));MemcachedClient client = builder.build();/*** 第一個參數指定遞增的key名稱, 第二個參數指定遞增的幅度大小, 第三個參數指定當key不存在的情況下的初始值。* 兩個參數的重載方法省略了第三個參數,默認指定為0。*/assert (1 == client.incr("a", 5, 1));assert (6 == client.incr("a", 5));assert (10 == client.incr("a", 4));assert (9 == client.decr("a", 1));assert (7 == client.decr("a", 2));}@Testpublic void counter() throws Exception {MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));MemcachedClient client = builder.build();Counter counter = client.getCounter("counter", 0);counter.incrementAndGet();counter.decrementAndGet();counter.addAndGet(-10);}public void auth() throws Exception {MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));builder.addAuthInfo(AddrUtil.getOneAddress("localhost:11211"),AuthInfo.typical("cacheuser", "123456"));// Must use binary protocolbuilder.setCommandFactory(new BinaryCommandFactory());MemcachedClient client = builder.build();}public void nioPool() throws Exception {MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11211"));builder.setConnectionPoolSize(5);}/***這里應該安裝kestrel消息服務器,才能使用如下API生效* @throws IOException* @throws MemcachedException * @throws InterruptedException * @throws TimeoutException */@Testpublic void testGet() throws IOException, TimeoutException, InterruptedException, MemcachedException{MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11212"));MemcachedClient client = builder.build();String value = client.get("1");System.out.println("hello=" + value);}@Testpublic void testGet2() throws IOException, TimeoutException, InterruptedException, MemcachedException{MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("localhost:11212"));MemcachedClient client = builder.build();String value = client.get("srp_"+MD5Util.MD5("3rdsearch_周杰倫"));System.out.println(value);} }轉自:http://javacrazyer.iteye.com/blog/1840119
轉載于:https://www.cnblogs.com/davidwang456/p/3688237.html
總結
以上是生活随笔為你收集整理的XMemcached使用示例--转的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: rsync+inotify实现实时同步案
- 下一篇: FactoryBean的使用--转