标签:
之前学习.net缓存的时候,已经讲过memcached,对于其集群、并发和内存回收等问题,都讲过,这里不再赘述,有兴趣的可以看这篇博客:分布式缓存Memcache和Redis。本篇主要讲解是使用java语言操作memcached。
java_memcached-release.jar;commons-pool.jar;slf4j-api.jar;slf4j-simple.jar(demo)
package com.tgb.testmemcached;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;
public class TestMemcachedClient {
SockIOPool sockIOPool = SockIOPool.getInstance();
MemCachedClient memCacheClient = new MemCachedClient();
@Before
public void init(){
String[] servers = {"192.168.24.131:11211"};
Integer[] weights ={3};
sockIOPool.setServers(servers);
sockIOPool.setWeights(weights);
sockIOPool.setInitConn(5);
sockIOPool.setMinConn(5);
sockIOPool.setMaxConn(20);
sockIOPool.setMaxIdle(1000*60*60*6);
sockIOPool.setMaintSleep(30);
sockIOPool.setNagle(false);
sockIOPool.setSocketTO(3000);
sockIOPool.setSocketConnectTO(0);
sockIOPool.initialize();
// memCacheClient.setCompressEnable(true);
// memCacheClient.setCompressThreshold(64*1024);
}
@Test
public void testAdd(){
//将数据放入缓存
memCacheClient.set("test1", "test1");
//将数据放入缓存,并设置失效时间
Date date = new Date(2000000);
memCacheClient.set("test2", "test2",date);
System.out.println("添加成功");
}
@Test
public void testGet(){
String strValue1 = memCacheClient.get("test1").toString();
String strValue2 = memCacheClient.get("test2").toString();
System.out.println(strValue1 + " " + strValue2);
}
@Test
public void testDelete(){
boolean flag = memCacheClient.delete("test1");
System.out.println(flag);
String strValue1 = memCacheClient.get("test1").toString();
System.out.println(strValue1);
}
@Test
public void testAdd2(){
//不对key做编码
memCacheClient.setSanitizeKeys(false);
memCacheClient.add("aa@163.com", "青山");
String strName = memCacheClient.get("aa@163.com").toString();
System.out.println(strName);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/jiben2qingshan/article/details/47173515