一、安装
我是在window下安装的memcached,选择的是1.4.4版本,安装起来简单点,安装教程链接。
二、MemcachedClient客户端API使用
使用MemcachedClient连接memcached,默认端口为11211.
2.1 Java连接memcached
import java.io.IOException;
import java.net.InetSocketAddress;
/**
* Created by wzj on 2018/6/5.
*/
public class MemcachedTest
{
public static void main(String[] args) throws IOException
{
// 本地连接 Memcached 服务
MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
System.out.println("Connection to server sucessful.");
// 关闭连接
mcc.shutdown();
}
}
2.2 set插入数据
set的方法签名为,第二个参数是过期时间,单位是秒
public Future<Boolean> set(String key, int exp, Object o)
重复的set操作,会覆盖之前的值。
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
/**
* Created by wzj on 2018/6/5.
*/
public class MemcachedTest
{
public static void main(String[] args) throws IOException, ExecutionException, InterruptedException
{
MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
Future<Boolean> set = mcc.set("key1", 10, "hello");
//查看存储状态
System.out.println(set.get());
mcc.set("key2",2,4);
System.out.println(mcc.get("key1"));
int v