今天拿到一台幹淨的linux虛拟器,安裝memcache,首先安裝libevent庫。
wget https://github.com/downloads/libevent/libevent/libevent-1.4.14b-stable.tar.gz
tar xvzf libevent-1.4.14b-stable.tar.gz
./configure
make
make install
然後,編譯、安裝、配置Memcached,執行如下指令行:
wget http://www.memcached.org/files/memcached-1.4.20.tar.gz
tar xvzf memcached-1.4.20.tar.gz
ln -s /usr/local/memcached-1.4.20 /usr/local/memcached
./configure --with-libevent=/usr/local/libevent/
make
make install
安裝過程中遇見這個問題:/usr/local/memcached/bin/memcached: error while loading shared libraries: libevent-1.4.so.2: cannot open shared object file: No such file or directory
解決類似問題的步驟:
1. 首先 find / -name libevent-1.4.so.2 找到缺少的連結檔案到底在那兒。
2. LD_DEBUG=libs /usr/local/bin/memcached -v
3. 從Debug資訊中就知道程式去哪裡找連結庫了。我這邊程式去 trying file=/usr/lib/libevent-1.4.so.2 而我的連結庫的實際存儲位置是 /usr/local/lib/libevent-1.4.so.2
4. 做一個軟連接配接 ln -s /usr/local/lib/libevent-1.4.so.2 /usr/lib/libevent-1.4.so.2
5. 搞定。
最後啟動memcache :
/usr/local/bin/memcached -d -m 2014 -I 20m -u root -p 12800 -c 1024 -t20
寫個小程式驗證一下memecahe是否可以正常使用,輸出都内容正确就OK
package com.testpai;
import net.spy.memcached.AddrUtil;
import net.spy.memcached.BinaryConnectionFactory;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.internal.OperationFuture;
public class TestMemcached {
public static void main(String[] args) throws Exception {
String address = "10.6.2.95:12800";
MemcachedClient client = new MemcachedClient(new BinaryConnectionFactory(),
AddrUtil.getAddresses(address));
String key = "magic_words";
int exp = 3600;
String o = "hello";
// set
OperationFuture<Boolean> setFuture = client.set(key, exp, o);
if(setFuture.get()) {
// get
System.out.println(client.get(key));
// append
client.replace(key, exp, " the world!");
System.out.println(client.get(key));
// prepend
client.prepend(exp, key, "Stone, ");
System.out.println(client.get(key));
// replace
o = "This is a test for spymemcached.";
OperationFuture<Boolean> replaceFuture = client.replace(key, exp, o);
if(replaceFuture.get()) {
System.out.println(client.get(key));
// delete
client.delete(key);
System.out.println(client.get(key));
}
}
client.shutdown();
}
}