1. 安装
brew install memcached
==> Installing dependencies for memcached: openssl and libevent
...
==> memcached
To have launchd start memcached now and restart at login:
brew services start memcached
Or, if you don't want/need a background service you can just run:
/usr/local/opt/memcached/bin/memcached
- 可以看出,安装memached的需要首先安装依赖openssl和libevent,这种依赖关系也可以用brew info来查看
2. 启动
可以通过brew services start memcached 来启动,也可手动启动,例如:
memcached -d -m 2048 -l 127.0.0.1 -p 11211
其中,-d表示后台运行,-m表示内存大小,-l表示访问地址, -p表示端口
3. 测试
使用Java来测试一下memcached。
a. 首先maven中加入常用的memcached客户端包Spymemcached
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.10.3</version>
</dependency>
b. 然后写一个测试类
public class Memcached {
private static MemcachedClient mcc;
public static void main(String[] args) {
try {
// 连接memcached
mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
System.out.println("Connection to server successfully.");
// 存储数据
Future fo = mcc.set("name", 10, "Michael");
// 查看存储状态
System.out.println("set status:" + fo.get());
// 输出值
System.out.println("Name value in cache - " + mcc.get("name"));
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally{
mcc.shutdown();
}
}
}
c. 运行输出结果
Connection to server successfully.
set status:true
Name value in cache - Michael