a simple memcached client Demo

本文探讨了在语音系统中引入缓存机制的重要性,并对比了ehcache与Memcached的特点。最终选择Memcached作为缓存解决方案,并提供了Java客户端的配置及使用示例。
在当前的一个语音系统中,需要频繁进行I/O操作, 为了应付未来可能出现的高并发访问, 初步计划引入缓存机制。
在诸多缓存中, ehcache口碑不错, 我之前也写过一篇文章介绍ehcache的使用:
http://lcllcl987.iteye.com/blog/222693

但ehcache不是一个分布式缓存解决方案。
所以, 就初选memcached了:
http://www.danga.com/memcached/

memcached的安装交给google,略过不表。


下面是两个memcached client的java实现:
http://www.whalin.com/memcached/
http://code.google.com/p/spymemcached/


http://www.whalin.com/memcached/
为例, 它的文档不错, 就不多说了。 test如下:
  1. packageco.cache;
  2. importcom.danga.MemCached.MemCachedClient;
  3. importcom.danga.MemCached.SockIOPool;
  4. publicclassMyMemCachedClient
  5. {
  6. //createastaticclientasmostinstallsonlyneed
  7. //asingleinstance
  8. privatestaticMemCachedClientmemCachedClient=newMemCachedClient();
  9. //setupconnectionpoolonceatclassload
  10. static
  11. {
  12. //serverlistandweights
  13. String[]servers={"192.168.0.55:11211"};
  14. Integer[]weights={3};
  15. //grabaninstanceofourconnectionpool
  16. SockIOPoolpool=SockIOPool.getInstance();
  17. //settheserversandtheweights
  18. pool.setServers(servers);
  19. pool.setWeights(weights);
  20. //setsomebasicpoolsettings
  21. //5initial,5min,and250maxconns
  22. //andsetthemaxidletimeforaconn
  23. //to6hours
  24. pool.setInitConn(5);
  25. pool.setMinConn(5);
  26. pool.setMaxConn(250);
  27. pool.setMaxIdle(1000*60*60*6);
  28. //setthesleepforthemaintthread
  29. //itwillwakeupeveryxsecondsand
  30. //maintainthepoolsize
  31. pool.setMaintSleep(30);
  32. //setsomeTCPsettings
  33. //disablenagle
  34. //setthereadtimeoutto3secs
  35. //anddon'tsetaconnecttimeout
  36. pool.setNagle(false);
  37. pool.setSocketTO(3000);
  38. pool.setSocketConnectTO(0);
  39. //initializetheconnectionpool
  40. pool.initialize();
  41. //letssetsomecompressiononfortheclient
  42. //compressanythinglargerthan64k
  43. memCachedClient.setCompressEnable(true);
  44. memCachedClient.setCompressThreshold(64*1024);
  45. }
  46. publicstaticMemCachedClientgetMemCachedClient()
  47. {
  48. returnmemCachedClient;
  49. }
  50. //fromhereondown,youcancallanyoftheclientcalls
  51. publicstaticvoidexamples()
  52. {
  53. memCachedClient.set("foo","ThisisatestString");
  54. Stringbar=(String)memCachedClient.get("foo");
  55. }
  56. publicstaticvoidmain(String[]args)
  57. {
  58. MyMemCachedClient.getMemCachedClient().set("foo","ThisisatestString.");
  59. Stringbar=(String)MyMemCachedClient.getMemCachedClient().get("foo");
  60. System.out.println(bar);
  61. }
  62. }
  63. 和ehcache不同的是,memcached似乎只采用LRU算法, 还对付cache满员的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值