Redis如何存储对象与集合示例详解

前言

本文介绍了Java利用Redis实现消息队列的示例代码,分享给大家,具体如下:

大家都知道在项目中,缓存以及mq消息队列可以说是不可或缺的2个重要技术。前者主要是为了减轻数据库压力,大幅度提升性能。后者主要是为了提高用户的体验度,我理解的是再后端做的一个ajax请求(异步),并且像ribbmitmq等消息队列有重试机制等功能。

应用场景

这里主要讲redis如何把对象,集合存入,并且取出。下面话不多说了,来一起看看详细的介绍吧。

为什么要用redis?

1.在启动类上加入如下代码

二进制存储、java序列化传输、IO连接数高、连接频繁

private Jedis jedis;private JedisPoolConfig config;private JedisShardInfo sharInfo;@Beanpublic Jedis jedis(){//连接redis服务器,192.168.0.100:6379// jedis = new Jedis("192.168.0.100", 6379);// //权限认证// jedis.auth("123456");// 操作单独的文本串config = new JedisPoolConfig(); config.setMaxIdle(1000);//最大空闲时间config.setMaxWaitMillis(1000); //最大等待时间config.setMaxTotal(500); //redis池中最大对象个数sharInfo = new JedisShardInfo("192.168.0.100", 6379); sharInfo.setPassword("123456"); sharInfo.setConnectionTimeout(5000);//链接超时时间jedis = new Jedis(sharInfo);return jedis; } 

一、序列化

2.在application.yml当中加入redis配置

这里编写了一个java序列化的工具,主要是将对象转化为byte数组,和根据byte数组反序列化成java对象; 主要是用到了ByteArrayOutputStream和ByteArrayInputStream; 注意:每个需要序列化的对象都要实现Serializable接口;

spring: redis: database: 0 host: 101.132.191.77 port: 6379 password: 123456 pool: max-idle: 8 #连接池最大连接数 min-idle: 0 # 连接池中的最小空闲连接 max-active: 8 # 连接池最大阻塞等待时间 max-wait: -1 # 连接池中的最大空闲连接 timeout: 5000 # 连接超时时间 

其代码如下:

3.新建SerializeUtil类,这个类主要是为了将对象序列化redis当中

package Utils;
import java.io.*;
/**
 * Created by Kinglf on 2016/10/17.
 */
public class ObjectUtil {
 /**
  * 对象转byte[]
  * @param obj
  * @return
  * @throws IOException
  */
 public static byte[] object2Bytes(Object obj) throws IOException{
  ByteArrayOutputStream bo=new ByteArrayOutputStream();
  ObjectOutputStream oo=new ObjectOutputStream(bo);
  oo.writeObject(obj);
  byte[] bytes=bo.toByteArray();
  bo.close();
  oo.close();
  return bytes;
 }
 /**
  * byte[]转对象
  * @param bytes
  * @return
  * @throws Exception
  */
 public static Object bytes2Object(byte[] bytes) throws Exception{
  ByteArrayInputStream in=new ByteArrayInputStream(bytes);
  ObjectInputStream sIn=new ObjectInputStream(in);
  return sIn.readObject();
 }
}
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream;/** public class SerializeUtil { 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) { }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; } } 

二、消息类(实现Serializable接口)

4.我封装了一个RedisServiceImpl类,主要是用对redis设值和取值

package Model;

import java.io.Serializable;

/**
 * Created by Kinglf on 2016/10/17.
 */
public class Message implements Serializable {

 private static final long serialVersionUID = -389326121047047723L;
 private int id;
 private String content;
 public Message(int id, String content) {
  this.id = id;
  this.content = content;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getContent() {
  return content;
 }
 public void setContent(String content) {
  this.content = content;
 }
}
import com.ys.util.redis.SerializeUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @Service public class RedisServiceImpl {@Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private Jedis jedis; public void setStr(String key, String value) { setStr(key, value, null); } public void setStr(String key, Object value, Long time) {if(value == null){ return; }if(value instanceof String){ String obj = (String) value; stringRedisTemplate.opsForValue().set(key, obj); }else if(value instanceof List){ List obj = (List) value; stringRedisTemplate.opsForList().leftPushAll(key,obj); }else if(value instanceof Map){ Map obj = (Map) value; stringRedisTemplate.opsForHash().putAll(key,obj); }if (time != null) stringRedisTemplate.expire(key, time, TimeUnit.SECONDS); } public Object getKey(String key) {return stringRedisTemplate.opsForValue().get(key); } public void delKey(String key) { stringRedisTemplate.delete(key); } public boolean del(String key) {return jedis.del(key.getBytes())0; } } 

三、Redis的操作

5.测试redis是否ok,编写redisController类

利用redis做队列,我们采用的是redis中list的push和pop操作;

import com.ys.service.impl.RedisServiceImpl; import com.ys.vo.IqProduct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Date; import java.util.List; @RestController public class RedisServiceController { @Autowired private RedisServiceImpl redisService; @RequestMapping(value = "/setredis") public String setredis(String keyredis){ redisService.setStr(keyredis,"2018年1月26日"); return "保存成功,请访问getredis查询redis"; } @RequestMapping(value = "/setObj") public String setObj(String keyredis){ IqProduct iqProduct = new IqProduct(); iqProduct.setSort(1); iqProduct.setTimestamp(new Date().getTime()); iqProduct.setProductName("productname"); // list.add(iqProduct); redisService.set(keyredis, iqProduct); return "保存成功,请访问getredis查询redis"; } @RequestMapping(value = "/getObj") public Object getObj(String keyredis){ Object object = redisService.get(keyredis); if(object !=null){ IqProduct iqProduct = (IqProduct) object; System. out.println(iqProduct.getProductName()); System. out.println(iqProduct.getId()); System. out.println(iqProduct.getTimestamp()); }return object; } @RequestMapping(value = "/delObj") public boolean delObj(String keyredis) {boolean del = redisService.del(keyredis); return del; } @RequestMapping(value = "/getredis") public String getredis(String keyredis){ String getredis = (String) redisService.getKey(keyredis); return "redis的key是==="+getredis; } @RequestMapping(value = "/delredis") public String delredis(String keyredis){ redisService.delKey(keyredis); return "删除成功,请通过getredis进行查询"; } @RequestMapping(value = "/setList") public String setList(String keyredis){ List list = new ArrayList();for (int i = 0;i10;i++){ IqProduct iqProduct = new IqProduct(); iqProduct.setSort(1); iqProduct.setTimestamp(new Date().getTime()); iqProduct.setProductName("productname"); list.add(iqProduct); } redisService.set(keyredis, list); return "保存成功,请访问getredis查询redis"; } @RequestMapping(value = "/getList") public Object getList(String keyredis){ Object object = redisService.get(keyredis); if(object !=null){ ListIqProduct iqProducts = (ListIqProduct) object; for (int i = 0;iiqProducts.size();i++){ IqProduct iqProduct = iqProducts.get(i); System. out.println(iqProduct.getProductName()); System. out.println(iqProduct.getId()); System. out.println(iqProduct.getTimestamp()); } }return object; } @RequestMapping(value = "/delList") public boolean delList(String keyredis) { boolean del = redisService.del(keyredis);return del; } } 

结合队列的特点:

6.测试结果

只允许在一端插入新元素只能在队列的尾部FIFO:先进先出原则Redis中lpush头入(rpop尾出)或rpush尾入(lpop头出)可以满足要求,而Redis中list药push或 pop的对象仅需要转换成byte[]即可

总结

java采用Jedis进行Redis的存储和Redis的连接池设置

本文由皇家赌场手机版发布于首页,转载请注明出处:Redis如何存储对象与集合示例详解

相关阅读