memcache 怎么存储的对象

memchache 将对象序列化后保存

memcahce将值序列化成字节数组,然后存储到缓存中。

如下例,我们将user对象序列化到文件a.txt中,同时将user保存到缓存中,通过比较文件和缓存中的值
发现,两者是一样的。

public class User implements Serializable{

    private String name;
    private String address;



    public User(String name, String address) {
        super();
        this.name = name;
        this.address = address;
    }
}
public static void main(String[] args) throws InterruptedException, ExecutionException, FileNotFoundException, IOException {
         MemcachedClient mcc =  null;
          try{
             // 本地连接 Memcached 服务
              mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
             System.out.println("Connection to server sucessful.");



          }catch(Exception ex){
             System.out.println( ex.getMessage() );
          }

          User u = new User("junwang","qingdao city");

          ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("a.txt")) );
          oos.writeObject(u);


          Future fo =  mcc.set("myuser", 5*60*1000, u);
          // 查看存储状态
          System.out.println("set status:" + fo.get());

          // 输出值
          System.out.println("myuser value in cache - " + mcc.get("myuser"));

          // 关闭连接
           mcc.shutdown();
       }

这里写图片描述

查看源代码

查看源代码,可以发现正是将对象序列化,然后保存。证明了我们上述的猜想。

BaseSerializingTranscoder.java

protected byte[] serialize(Object o) {
    if (o == null) {
      throw new NullPointerException("Can't serialize null");
    }
    byte[] rv=null;
    ByteArrayOutputStream bos = null;
    ObjectOutputStream os = null;
    try {
      bos = new ByteArrayOutputStream();
      os = new ObjectOutputStream(bos);
      os.writeObject(o);
      os.close();
      bos.close();
      rv = bos.toByteArray();
    } catch (IOException e) {
      throw new IllegalArgumentException("Non-serializable object", e);
    } finally {
      CloseUtil.close(os);
      CloseUtil.close(bos);
    }
    return rv;
  }

结论

值的存储,都是序列化成字节数组,然后保存

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值