Nosql之Redis(二)---Java操作Redis存储自定义类型数据
Redis简介
Redis是一个开源,先进的key-value存储,并用于构建高性能,可扩展的Web应用程序的完美解决方案。
Redis从它的许多竞争继承来的三个主要特点:
Redis操作
使用java语言操作redis需要引用jedis的jar包,我用的版本是2.8.0【点击下载】。Redis支持存储的数据类型有String,List,Map,Set,Hash及Zset。
由于简单的操作Redis的基本类型在网上很容易就找到一堆资料,所以今天笔者主要写如何使用redis存储自定义类型。
Redis中支持的基本类型String,而且在我试验的过程中发现无论是List还是Map也都只能放String类型的数据。所以如果我们想要存储自定义类型的数据的时候,不可避免的会有两个过程——序列化与反序列化。
代码
- //定义需要存储的数据
- StudentVo studentVo = newStudentVo();
- studentVo.setId(student.getId());
- studentVo.setApplyTeacherState(student.getApplyTeacherState());
- studentVo.setBornDate(student.getBornDate());
- studentVo.setHeadPic(student.getHeadPic());
- studentVo.setIntroduce(student.getIntroduce());
- studentVo.setIsTeacher(student.getIsTeacher());
- studentVo.setRealName(student.getRealName());
- studentVo.setNickName(student.getNickName());
- studentVo.setPhoNum(student.getPhoNum());
- jedis = new Jedis("XXX.56. XXX.XXX ",6379); //实例化一个新的jedis对象
- UUID uuid = UUID.randomUUID();
- String jSession = uuid.toString();
- studentVo.setSessionId(jSession); //jSession是用户登录过程中产生的唯一标识
- jedis.set(jSession.getBytes(),SerializationUtil.serialize(studentVo)); //SerializationUtil负责序列化与反序列化的类
- jedis.expire(jSession,3600); // 设置过期时间
- //上面描述的是如何存储自定义类型,下面是如何使用了
- //如果登录系统之后,系统访问链接后面都会带着一个UUID作为唯一标识,
- //例如:http://www.jrkj.org/itoo-jrkj-homepageset-web/index/63db86a4-12de-443d-bff0-23d4f6ab67c0
- byte[] bSession= jedis.get(sessionId.getBytes()); //sessionId是用户的唯一标识,
- StudentVo student = (StudentVo)SerializationUtil.deserialize(bSession); //通过反序列化就能够获取存储的数据
序列化与反序列化代码
- public classSerializationUtil {
- /**
- * 序列化
- *
- * @param object
- * @return
- */
- publicstatic 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) {
- }
- return null;
- }
- /**
- * 反序列化
- *
- * @param bytes
- * @return
- */
- publicstatic Object deserialize(byte[] bytes) {
- ByteArrayInputStream bais = null;
- try {
- bais = new ByteArrayInputStream(bytes);
- ObjectInputStream ois = new ObjectInputStream(bais);
- return ois.readObject();
- } catch (Exception e) {
- }
- return null;
- }
- }
小结
Jedis操作redis存储定义一类型主要就是一个序列化与反序列化的过程,这个之后你就可以存储任意类型的数据了。不妨自己写个demo试试,如何安装redis之前的博客中已经有介绍,也可以在网上找找相关的教程。
笔者在这里提前祝大家新春快乐,希望新的一年里,大家心想事成、阖家幸福!