日期:2014-05-16 浏览次数:20780 次
1.下载
http://www.monkey.org/~provos/libevent-2.0.12-stable.tar.gz
http://memcached.googlecode.com/files/memcached-1.4.5.tar.gz
?
2.安装
安装libevent
tar xvf libevent-2.0.12-stable.tar.gz
cd libevent-2.0.12-stable
./configure -prefix=/usr
make
make install
查看安装是否成功
ls -all /usr/lib | grep libevent
?
?
安装memcached
tar xvf memcached-1.4.5.tar.gz
cd memcached-1.4.5
./configure -with-libevent=/usr
make
make install
查看安装是否成功
ls -all/usr/local/bin/mem*
?
3.开防火墙,假设使用端口11211
?
vi /etc/sysconfig/iptables
添加
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 11211 -j ACCEPT
保存退出
重启服务使刚才的设置生效
service iptables restart
?
?
搞定
?
启动memcached
/usr/local/bin/memcached -d -m 128 -u root -l 192.168.49.130 -p 11211 -c 1024?-P /tmp/memcached.pid
参数说明
?
-d 启动一个守护进程
-m 分配给Memcache使用的内存数量(MB)
-u 运行Memcache的用户
-l 是监听的服务器IP地址
-p Memcache监听的端口
-c 最大运行的并发连接数,默认是1024
-P 设置保存Memcache的pid文件
?
?
关闭memcached
1.查询memcached的pid
cat /tmp/memcached.pid
显示22376
如果没指定-P参数,则先ps -A查看进程,找出memcached的pid,例如我这里显示的是
?
22182 ? ? ? ? ?00:00:00 memcached
?
2.kill pid
例如kill?22182
?
将memcached加入启动项
vi /etc/rc.d/rc.local
在最后加入启动命令
/usr/local/bin/memcached -d -m 128 -u root -l 192.168.49.130 -p 11211 -c 1024?-P /tmp/memcached.pid
保存退出
?
添加到服务
vim /etc/rc.d/rc.local
添加
/usr/local/bin/memcached -d -m 128 -u root -l 192.168.49.130 -p 11211 -c 1024?-P /tmp/memcached.pid
?
?
测试
?
package com.gary.test; import com.danga.MemCached.MemCachedClient; import com.danga.MemCached.SockIOPool; public class TestMemcached { String[] servers = { "192.168.49.130:11211" }; Integer[] weights = { 3 }; MemCachedClient mcc = new MemCachedClient(); SockIOPool pool = SockIOPool.getInstance(); public TestMemcached() { init(); } private void init(){ pool.setServers(servers); pool.setWeights(weights); pool.setInitConn(5); pool.setMinConn(5); pool.setMaxConn(250); pool.setMaxIdle(30); pool.setMaintSleep(30); pool.initialize(); } public void testPut() { for (int i = 1; i <= 3; i++) { // 如果以前存在,则不去更新 boolean b = mcc.add("key" + i, "value" + i); System.out.println("key" + i +" - result: " + b); } } public void testReplace() { // 如果key不存在,则返回flase,更新失败 boolean b = mcc.replace("key2", "newValue"); System.out.println("update " + b); } public void testGet() { Object obj = mcc.get("key2"); System.out.println(obj); } public void testDelete() { Object key3 = mcc.get("key3"); System.out.println("key3:" + key3); mcc.delete("key3"); System.out.println("after delete"); Object key3now = mcc.get("key3"); System.out.println("key3 now:" + key3now); } public static void main(String args[]) { TestMemcached tm = new TestMemcached(); tm.testPut(); tm.testReplace(); tm.testGet(); tm.testDelete(); //最后关闭池 tm.pool.shutDown(); } }
?
?测试结果
?
key1 - result: true key2 - result: true key3 - result: true update true newValue key3:value3 after delete key3 now:null?