配置好Magent+memcached後,很明顯數據之間的輸入與輸出都是通過代理服務器的,magent是做代理服務器的很明顯java在memecached的調用驅動在magent同樣適用。
這裡選擇SpyMemcached來緩存數據.
1.定義一個User
注意:類型必須序列化
package memdemo;
import java.io.Serializable;
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
2.寫一個測試類
package memdemo;
import java.io.IOException;
import java.net.InetSocketAddress;
import org.junit.Test;
import net.spy.memcached.MemcachedClient;
public class SpyMemcachedTest {
private static MemcachedClient client;
static{
InetSocketAddress ia=new InetSocketAddress("127.0.0.1", 2222);
try {
client=new MemcachedClient(ia);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void add(){
client.add("swder", 1, "maybo");
System.out.println(client.get("swder").toString());
}
@Test
public void addUser(){
User user=new User();
user.setAge(23);
user.setId(1);
user.setName("maybo");
//client.add("user123", 0, user);
System.out.println(client.get("user123").toString());
}
}