最近也是用到了Memcached,所以借这个机会把这个也保存一下
废话不多说,直接上代码:
首先maven中引入需要的jar
<!-- https://mvnrepository.com/artifact/com.googlecode.xmemcached/xmemcached -->
<dependency>
<groupId>com.googlecode.xmemcached</groupId>
<artifactId>xmemcached</artifactId>
<version>2.3.1</version>
</dependency>
然后创建一个类
package cp.pay.mj.utils;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;
public class MemCachedTest {
private static MemcachedClient cachedClient ; // memcached客户端单例
protected static MemCachedTest memCached = new MemCachedTest();
/**
* 初始化连接池
*/
static {
System.out.println("初始化连接池");
MemcachedClientBuilder builder = new XMemcachedClientBuilder(
AddrUtil.getAddresses ("需要的ip地址,及端口号"),new int[] {1});
try {
cachedClient = builder.build();
} catch (IOException e) {
e.printStackTrace();
}
}
protected MemCachedTest() {
}
public static MemCachedTest getInstance() {
return memCached;
}
public static boolean add(String key, Integer expire, Object value) throws Exception{
return cachedClient.add(key, expire, value);
}
public static boolean del(String key) throws Exception{
return cachedClient.delete(key);
}
/**
* 设置缓存中的对象(value),如果没有则插入,如果有则修改。
* @param key
* @param value
* @param expire
* @return
*/
public static void set(String key, Integer expire,Object value) {
try {
cachedClient.set(key, expire,value);
} catch (TimeoutException e) {
} catch (InterruptedException e) {
} catch (MemcachedException e) {
}
}
/**
* 该键的新值(new value),如果有则修改。
* @param key
* @param value
* @param expire
* @return
*/
public static Object get(String key) {
try {
return cachedClient.get(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
MemCachedTest.getInstance();
}
}
然后在controller中,引用刚才创建的类,初始化链接
private static MemCachedTest memCached = MemCachedTest.getInstance();
然后在需要存的时候调用
memCached.set(phone, 0, "hello world");//0是设置过期时间,0为永久有效
获取的时候用
memCached.get(phone);
memCached的具体语法和用法请参考:
http://www.runoob.com/memcached/memcached-set-data.html
如果都配置成功后,在tomcat启动的时候就会有初始化连接池的输出,注意IP一定要写正确