redis存储对象

2018-01-31 10:57:57来源:网络收集作者:程序诗人人点击

分享
redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set –有序集合)和hash(哈希类型)。在实际工作中需要将数据以对象的形式存储,实现如下:
配置redis可以参考http://blog.csdn.net/leo187/article/details/78704811
配置成功后进行如下操作
先创建一个测试对象goods
package com.project.entity;
import java.io.Serializable;
//实体实现序列化接口
public class EmallGoodsimplements Serializable{
private Integer goodsid;
private String goodsname;
public Integer getGoodsid() {
return goodsid;
}
public void setGoodsid(Integer goodsid) {
this.goodsid = goodsid;
}
public String getGoodsname() {
return goodsname;
}
public void setGoodsname(String goodsname) {
this.goodsname = goodsname == null ? null : goodsname.trim();
}
}
序列化、反序列化Util类
package com.project.controller.Redis;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtilNew {
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static Object unserialize( byte[] bytes) {
ByteArrayInputStream bais = null;
try {
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
}
return null;
}
}
实例调用
public void selectReviewsByGoodsId(HttpServletRequest request){
EmallGoods goodsInfo = new EmallGoods();
goodsInfo.setGoodsid(1000);
goodsInfo.setGoodsname("晨光 M&G 中性笔 K35 0.5mm(黑色)12支/盒(替芯:G-5)");
try {
Jedis jedis = new Jedis();
//以商品id为key,商品对象为value存储jedis.set(goodsInfo.getGoodsid().toString().getBytes(),SerializeUtilNew.serialize(goodsInfo));
byte[] value = jedis.get(goodsInfo.getGoodsid().toString().getBytes());
Object object = SerializeUtilNew.unserialize(value);
if(object!= null){
EmallGoods goo=(EmallGoods) object;
System. out.println(goo.getGoodsname());
System. out.println(goo.getGoodsid());
}
} catch (Exception e) {
System.out.println("登录无法更新该商品缓存");
}
}

-打印输出:


晨光 M&G 中性笔 K35 0.5mm(黑色)12支/盒(替芯:G-5)
1000

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台