小奋斗 - 轻松学习从此开始!
IT小奋斗群 QQ群:62017228

Java通过SpyMemcached来缓存数据

配置好Magent+memcached后,很明显数据之间的输入与输出都是通过代理服务器的,magent是做代理服务器的很明显java在memecached的调用驱动在magent同样适用.

这里选择SpyMemcached来缓存数据.

1.定义一个User

    注意:类型必须序列化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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.写一个测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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());
}
}

我来评几句
登录后评论

已发表评论数(0)