任务:在现有的项目中添加memcache以减少数据库压力,就先搭建了一个测试环境
系统:Ubuntu14
步骤:memcached依赖libevent包,我这个系统已经有了,就没有安装
安装memcached : apt-get install memcached
修改配置: vim /etc/memcached.conf 将里面的 -l 127.0.0.1注释掉(不注释代表只能本机访问)
启动memcached: /etc/init.d/memcached start
测试: telnet localhost 11211 提示 connected to memcached成功
项目中用的是xmemcached,把jar包导入项目,编写测试代码:
输出:略
下一步是要建立一个双机高可用的,准备用keepalived,到时候再写
系统:Ubuntu14
步骤:memcached依赖libevent包,我这个系统已经有了,就没有安装
安装memcached : apt-get install memcached
修改配置: vim /etc/memcached.conf 将里面的 -l 127.0.0.1注释掉(不注释代表只能本机访问)
启动memcached: /etc/init.d/memcached start
测试: telnet localhost 11211 提示 connected to memcached成功
项目中用的是xmemcached,把jar包导入项目,编写测试代码:
public static void main(String[] args) {
MemcachedClientBuilder builder = new XMemcachedClientBuilder(
AddrUtil.getAddresses("192.168.64.129:11211"));
MemcachedClient memcachedClient = null;
try {
memcachedClient = builder.build();
memcachedClient.set("hello", 0, "Hello,xmemcached");
String value = memcachedClient.get("hello");
System.out.println("hello=" + value);
memcachedClient.delete("hello");
value = memcachedClient.get("hello");
System.out.println("hello=" + value);
} catch (MemcachedException e) {
System.err.println("MemcachedClient operation fail");
e.printStackTrace();
} catch (TimeoutException e) {
System.err.println("MemcachedClient operation timeout");
e.printStackTrace();
} catch (InterruptedException e) {
// ignore
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// close memcached client
memcachedClient.shutdown();
} catch (IOException e) {
System.err.println("Shutdown MemcachedClient fail");
e.printStackTrace();
}
}
输出:略
下一步是要建立一个双机高可用的,准备用keepalived,到时候再写