要連線到memcache伺服器,需要使用telnet命令到主機和埠名稱。
memcached 的 telnet 命令的基本語法如下所示:
$telnet HOST PORT
在這裡,Host 和Port 是memcached伺服器執行的IP和埠
下面給出的範例演示如何連線到memcached伺服器,並執行一個簡單的set和get命令。在這個例子中,假定memcached伺服器在主機IP是127.0.0.1,埠11211上執行
$telnet 127.0.0.1 11211 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. // now store some data and get it from memcached server set yiibai 0 900 9 memcached STORED get yiibai VALUE yiibai 0 9 memcached END
要從Java程式連線memcached伺服器,需要新增memcached的jar包到類路徑,如圖前面的章節。
import net.spy.memcached.MemcachedClient; public class MemcachedJava { public static void main(String[] args) { //Connecting to Memcached server on localhost MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211)); System.out.println("Connection to server sucessfully"); //not set data into memcached server System.out.println("set status:"+mcc.set("yiibai", 900, "memcached").done); //Get value from cache System.out.println("Get from Cache:"+mcc.get("yiibai")); } }
在上面的程式,假設memcached伺服器的主機IP是127.0.0.1,並在埠11211上執行。
當上述程式編譯和執行,它提供了以下的輸出:
Connection to server successfully set status:true Get from Cache:memcached