标签:
import com.whalin.MemCached.MemCachedClient; import com.whalin.MemCached.SockIOPool; public class TestMemcached { public static void main(String[] args) { /*初始化SockIOPool,管理memcached的连接池*/ String[] servers = { "120.143.23.240:12000"};//注意这里的memcached可以是多个 SockIOPool pool = SockIOPool.getInstance(); pool.setServers(servers); pool.setFailover(true); pool.setInitConn(10);//初始链接数 pool.setMinConn(5);//最小链接数 pool.setMaxConn(250);//最大链接数 pool.setMaintSleep(30); pool.setNagle(false); pool.setSocketTO(3000);//超时时间 pool.setAliveCheck(true); pool.initialize(); /*建立MemcachedClient实例*/ MemCachedClient memCachedClient = new MemCachedClient(); for (int i = 0; i < 5; i++) { /*将对象加入到memcached缓存*/ boolean success = memCachedClient.set("" + i, "Hello!"); boolean yes = memCachedClient.set("yuanyirui", "ni shi yi ge da cai bi!"); /*从memcached缓存中按key值取对象*/ String result = (String) memCachedClient.get("" + i); System.out.println(String.format("set( %d ): %s", i, success)); System.out.println(String.format("get( %d ): %s", i, result)); } } }每个缓存都是一个server;
import java.net.InetSocketAddress; import java.util.concurrent.Future; import net.spy.memcached.MemcachedClient; public class MClientSet { public static void main(String[] args){ try{ /*建立MemcachedClient 实例,并指定memcached服务的IP地址和端口号*/ MemcachedClient mc = new MemcachedClient(new InetSocketAddress("120.143.23.240", 12000)); Future<Boolean> b = null; /*将key值,过期时间(秒)和要缓存的对象set到memcached中*/ b = mc.set("yuanyirui", 900, "ni shi yi ge da cai niao11"); // Object c = mc.get("yuanyirui"); // System.out.println(c.toString()); if(b.get().booleanValue()==true){ mc.shutdown();// } } catch(Exception ex){ ex.printStackTrace(); } } }3.补充知识:五种基本 memcached 命令
add
命令才会向缓存中添加一个键值对。如果缓存中已经存在键,则之前的值将仍然保持相同,并且您将获得响应;replace
命令才会替换缓存中的键。如果缓存中不存在键,将从
memcached 服务器接受到一条 NOT_STORED 响应;delete
,如果该键存在于缓存中,则删除该值。如果不存在,则返回一条NOT_FOUND 消息;telnet localhost 112115.2 启动命令:
memcached -d -p 12000 -u nobody -c 1024 -m64
-p 监听的端口5.3 查看:
ps -ef|grep memcached
5.4 关掉memcached标签:
原文地址:http://blog.csdn.net/u010235716/article/details/51361120