应用场景

最近在公司做项目,需要对聊天内容进行存储,考虑到数据库查询的IO连接数高、连接频繁的因素,决定利用缓存做。

从网上了解到redis可以对所有的内容进行二进制的存储,而java是可以对所有对象进行序列化的,序列化的方法会在下面的代码中提供实现。

序列化

这里我编写了一个java序列化的工具,主要是对对象转换成byte[],和根据byte[]数组反序列化成java对象;

主要是用到了ByteArrayOutputStream和ByteArrayInputStream;

需要注意的是每个自定义的需要序列化的对象都要实现Serializable接口;

其代码如下:

package com.bean.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectUtil {
/**对象转byte[]
* @param obj
* @return
* @throws IOException
*/
public static byte[] objectToBytes(Object obj) throws Exception{
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 bytesToObject(byte[] bytes) throws Exception{
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream sIn = new ObjectInputStream(in);
return sIn.readObject();
}
}

定义一个消息类,主要用于接收消息内容和消息下表的设置。

package com.bean;

import java.io.Serializable;

/**定义消息类接收消息内容和设置消息的下标
* @author lenovo
*
*/
public class Message implements Serializable{
private static final long serialVersionUID = 7792729L;
private int id;
private String 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;
}
}

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

结合队列的特点:

  • 只允许在一端插入
  • 新元素只能在队列的尾部
  • FIFO:先进先出原则

    redis中lpush(rpop)或rpush(lpop)可以满足要求,而redis中list 里要push或pop的对象仅需要转换成byte[]即可

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

    package com.redis.util;
    
    import java.util.List;
    import java.util.Map;
    import java.util.Set; import redis.clients.jedis.Jedis;
    import redis.clients.jedis.JedisPool;
    import redis.clients.jedis.JedisPoolConfig; public class JedisUtil { private static String JEDIS_IP;
    private static int JEDIS_PORT;
    private static String JEDIS_PASSWORD;
    //private static String JEDIS_SLAVE; private static JedisPool jedisPool; static {
    Configuration conf = Configuration.getInstance();
    JEDIS_IP = conf.getString("jedis.ip", "127.0.0.1");
    JEDIS_PORT = conf.getInt("jedis.port", 6379);
    JEDIS_PASSWORD = conf.getString("jedis.password", null);
    JedisPoolConfig config = new JedisPoolConfig();
    config.setMaxActive(5000);
    config.setMaxIdle(256);//20
    config.setMaxWait(5000L);
    config.setTestOnBorrow(true);
    config.setTestOnReturn(true);
    config.setTestWhileIdle(true);
    config.setMinEvictableIdleTimeMillis(60000l);
    config.setTimeBetweenEvictionRunsMillis(3000l);
    config.setNumTestsPerEvictionRun(-1);
    jedisPool = new JedisPool(config, JEDIS_IP, JEDIS_PORT, 60000);
    } /**
    * 获取数据
    * @param key
    * @return
    */
    public static String get(String key) { String value = null;
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    value = jedis.get(key);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    } return value;
    } public static void close(Jedis jedis) {
    try {
    jedisPool.returnResource(jedis); } catch (Exception e) {
    if (jedis.isConnected()) {
    jedis.quit();
    jedis.disconnect();
    }
    }
    } /**
    * 获取数据
    *
    * @param key
    * @return
    */
    public static byte[] get(byte[] key) { byte[] value = null;
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    value = jedis.get(key);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    } return value;
    } public static void set(byte[] key, byte[] value) { Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    jedis.set(key, value);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    }
    } public static void set(byte[] key, byte[] value, int time) { Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    jedis.set(key, value);
    jedis.expire(key, time);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    }
    } public static void hset(byte[] key, byte[] field, byte[] value) {
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    jedis.hset(key, field, value);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    }
    } public static void hset(String key, String field, String value) {
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    jedis.hset(key, field, value);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    }
    } /**
    * 获取数据
    *
    * @param key
    * @return
    */
    public static String hget(String key, String field) { String value = null;
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    value = jedis.hget(key, field);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    } return value;
    } /**
    * 获取数据
    *
    * @param key
    * @return
    */
    public static byte[] hget(byte[] key, byte[] field) { byte[] value = null;
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    value = jedis.hget(key, field);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    } return value;
    } public static void hdel(byte[] key, byte[] field) { Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    jedis.hdel(key, field);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    }
    } /**
    * 存储REDIS队列 顺序存储
    * @param byte[] key reids键名
    * @param byte[] value 键值
    */
    public static void lpush(byte[] key, byte[] value) { Jedis jedis = null;
    try { jedis = jedisPool.getResource();
    jedis.lpush(key, value); } catch (Exception e) { //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally { //返还到连接池
    close(jedis); }
    } /**
    * 存储REDIS队列 反向存储
    * @param byte[] key reids键名
    * @param byte[] value 键值
    */
    public static void rpush(byte[] key, byte[] value) { Jedis jedis = null;
    try { jedis = jedisPool.getResource();
    jedis.rpush(key, value); } catch (Exception e) { //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally { //返还到连接池
    close(jedis); }
    } /**
    * 将列表 source 中的最后一个元素(尾元素)弹出,并返回给客户端
    * @param byte[] key reids键名
    * @param byte[] value 键值
    */
    public static void rpoplpush(byte[] key, byte[] destination) { Jedis jedis = null;
    try { jedis = jedisPool.getResource();
    jedis.rpoplpush(key, destination); } catch (Exception e) { //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally { //返还到连接池
    close(jedis); }
    } /**
    * 获取队列数据
    * @param byte[] key 键名
    * @return
    */
    public static List<byte[]> lpopList(byte[] key) { List<byte[]> list = null;
    Jedis jedis = null;
    try { jedis = jedisPool.getResource();
    list = jedis.lrange(key, 0, -1); } catch (Exception e) { //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally { //返还到连接池
    close(jedis); }
    return list;
    } /**
    * 获取队列数据
    * @param byte[] key 键名
    * @return
    */
    public static byte[] rpop(byte[] key) { byte[] bytes = null;
    Jedis jedis = null;
    try { jedis = jedisPool.getResource();
    bytes = jedis.rpop(key); } catch (Exception e) { //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally { //返还到连接池
    close(jedis); }
    return bytes;
    } public static void hmset(Object key, Map<String, String> hash) {
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    jedis.hmset(key.toString(), hash);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally {
    //返还到连接池
    close(jedis); }
    } public static void hmset(Object key, Map<String, String> hash, int time) {
    Jedis jedis = null;
    try { jedis = jedisPool.getResource();
    jedis.hmset(key.toString(), hash);
    jedis.expire(key.toString(), time);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally {
    //返还到连接池
    close(jedis); }
    } public static List<String> hmget(Object key, String... fields) {
    List<String> result = null;
    Jedis jedis = null;
    try { jedis = jedisPool.getResource();
    result = jedis.hmget(key.toString(), fields); } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally {
    //返还到连接池
    close(jedis); }
    return result;
    } public static Set<String> hkeys(String key) {
    Set<String> result = null;
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    result = jedis.hkeys(key); } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally {
    //返还到连接池
    close(jedis); }
    return result;
    } public static List<byte[]> lrange(byte[] key, int from, int to) {
    List<byte[]> result = null;
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    result = jedis.lrange(key, from, to); } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally {
    //返还到连接池
    close(jedis); }
    return result;
    } public static Map<byte[], byte[]> hgetAll(byte[] key) {
    Map<byte[], byte[]> result = null;
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    result = jedis.hgetAll(key);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace(); } finally {
    //返还到连接池
    close(jedis);
    }
    return result;
    } public static void del(byte[] key) { Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    jedis.del(key);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    }
    } public static long llen(byte[] key) { long len = 0;
    Jedis jedis = null;
    try {
    jedis = jedisPool.getResource();
    jedis.llen(key);
    } catch (Exception e) {
    //释放redis对象
    jedisPool.returnBrokenResource(jedis);
    e.printStackTrace();
    } finally {
    //返还到连接池
    close(jedis);
    }
    return len;
    } }

    Configuration主要用于读取redis配置信息

    package com.redis.util;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties; public class Configuration extends Properties { private static final long serialVersionUID = 50440463580273222L; private static Configuration instance = null; public static synchronized Configuration getInstance() {
    if (instance == null) {
    instance = new Configuration();
    }
    return instance;
    } public String getProperty(String key, String defaultValue) {
    String val = getProperty(key);
    return (val == null || val.isEmpty()) ? defaultValue : val;
    } public String getString(String name, String defaultValue) {
    return this.getProperty(name, defaultValue);
    } public int getInt(String name, int defaultValue) {
    String val = this.getProperty(name);
    return (val == null || val.isEmpty()) ? defaultValue : Integer.parseInt(val);
    } public long getLong(String name, long defaultValue) {
    String val = this.getProperty(name);
    return (val == null || val.isEmpty()) ? defaultValue : Integer.parseInt(val);
    } public float getFloat(String name, float defaultValue) {
    String val = this.getProperty(name);
    return (val == null || val.isEmpty()) ? defaultValue : Float.parseFloat(val);
    } public double getDouble(String name, double defaultValue) {
    String val = this.getProperty(name);
    return (val == null || val.isEmpty()) ? defaultValue : Double.parseDouble(val);
    } public byte getByte(String name, byte defaultValue) {
    String val = this.getProperty(name);
    return (val == null || val.isEmpty()) ? defaultValue : Byte.parseByte(val);
    } public Configuration() {
    InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("config.xml");
    try {
    this.loadFromXML(in);
    in.close();
    } catch (IOException e) {
    }
    }
    }

    测试redis队列

    package com.quene.test;
    
    import com.bean.Message;
    import com.bean.util.ObjectUtil;
    import com.redis.util.JedisUtil; public class TestRedisQuene {
    public static byte[] redisKey = "key".getBytes();
    static{
    init();
    }
    public static void main(String[] args) {
    pop();
    } private static void pop() {
    byte[] bytes = JedisUtil.rpop(redisKey);
    Message msg = (Message) ObjectUtil.bytesToObject(bytes);
    if(msg != null){
    System.out.println(msg.getId()+" "+msg.getContent());
    }
    } private static void init() {
    Message msg1 = new Message(1, "内容1");
    JedisUtil.lpush(redisKey, ObjectUtil.objectToBytes(msg1));
    Message msg2 = new Message(2, "内容2");
    JedisUtil.lpush(redisKey, ObjectUtil.objectToBytes(msg2));
    Message msg3 = new Message(3, "内容3");
    JedisUtil.lpush(redisKey, ObjectUtil.objectToBytes(msg3));
    } }
    测试结果如下:
    1   内容1
    2   内容2

    3   内容3

    转自http://www.itnose.net/detail/6284422.html

(转)java redis使用之利用jedis实现redis消息队列的更多相关文章

  1. Redis入门和Java利用jedis操作redis

    Redis入门和Java利用jedis操作redis Redis介绍 Redis 是完全开源的,遵守 BSD 协议,是一个高性能的 key-value 数据库. Redis 与其他 key - val ...

  2. php 利用activeMq+stomp实现消息队列

    php 利用activeMq+stomp实现消息队列 一.activeMq概述 ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线.ActiveMQ 是一个完全支持JMS1.1和J ...

  3. Redis(二)Jedis操作Redis

    如果测试连接的时候,报下面这个异常,可以参考下面的博客进行处理: Exception in thread "main" redis.clients.jedis.exceptions ...

  4. 八.利用springAMQP实现异步消息队列的日志管理

    经过前段时间的学习和铺垫,已经对spring amqp有了大概的了解.俗话说学以致用,今天就利用springAMQP来完成一个日志管理模块.大概的需求是这样的:系统中有很多地方需要记录操作日志,比如登 ...

  5. Redis使用总结(3):实现简单的消息队列

    参考Redis实现简单消息队列 Redis提供了两种方式来作消息队列.一个是使用生产者消费模式模式,另外一个方法就是发布订阅者模式.前者会让一个或者多个客户端监听消息队列,一旦消息到达,消费者马上消费 ...

  6. Java岗位面试题分享:jvm+分布式+消息队列+协议(已拿offer)

    个人近期面试情况 今年二月以来,我的面试除了一个用友的,基本其他都被毙了,可以说是非常残酷的.其中有很多自己觉得还面的不错的岗位,比如百度.跟谁学.好未来等公司.说实话,打击比较大. 情况基本上是从三 ...

  7. Redis Desktop Manager 利用ssh连接 Redis

    需开启6379端口,如果不设置密码,就忽略1,2步骤 第一步: 第二步: 第三步: 第四步: 第五步:

  8. .NetCore利用BlockingCollection实现简易消息队列

    前言 消息队列现今的应用场景越来越大,常用的有RabbmitMQ和KafKa. 我们用BlockingCollection来实现简单的消息队列. 实现消息队列 用Vs2017创建一个控制台应用程序.创 ...

  9. Redis(九)哨兵:Redis Sentinel

    Redis的主从复制模式下,一旦主节点由于故障不能提供服务,需要人工将从节点晋升为主节点,同时还要通知应用方更新主节点地址,对于很多应用场景这种故障处理的方式是无法接受的. Redis从2.8开始正式 ...

随机推荐

  1. css使absolute相对于父容器进行定位而不是以body(为什么绝对定位(absolute)的父级元素必须是相对定位(relative))

    借知乎的回答如下解释: 首先,我想告诉你的是,如果父级元素是绝对定位(absolute)或者没有设置,里面的绝对定位(absolute)自动以body定位.这句话是错的.正确的是:只要父级元素设了po ...

  2. HDU 5944 Fxx and string(暴力/枚举)

    传送门 Fxx and string Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Othe ...

  3. 【原创】自己动手写工具----XSmartNote [Beta 1.0]

    一.背景 有个朋友是在他们单位的市场部,手里的策划文案以及PPT,少则数百,多则上千,多年下来也是一笔不可小觑的财富,每一次新的策划都可以从以往的文案或PPT中“拿来主义”,有着很好的借鉴意义,但是这 ...

  4. thinkphp 命名空间

    什么是命名空间?从广义上来说,命名空间是一种封装事物的方法.在很多地方都可以见到这种抽象概念.例如,在操作系统中目录用来将相关文件分组,对于目录中的文件来说,它就扮演了命名空间的角色.具体举个例子,文 ...

  5. Set集合

    Set:无序(存储和取出数据不一致):唯一性(不可重复) Set是Collection的子类,所以Collection的方法Set都可以使用 HashSet:底层为哈希表,保证唯一性,依赖hashCo ...

  6. Lua IDE

    http://blog.csdn.net/visualcatsharp/article/details/37653107

  7. ORACLE常用数值函数、转换函数、字符串函数

    本文更多将会介绍三思在日常中经常会用到的,或者虽然很少用到,但是感觉挺有意思的一些函数.分二类介绍,分别是: 著名函数篇 -经常用到的函数 非著名函数篇-即虽然很少用到,但某些情况下却很实用 注:N表 ...

  8. [Asp.net]常见word,excel,ppt,pdf在线预览方案,有图有真相,总有一款适合你!

    引言 之前项目需要,查找了office文档在线预览的解决方案,顺便记录一下,方便以后查询. 方案一 直接在浏览器中打开Office文档在页面上的链接.会弹出如下窗口: 优点:主流浏览器都支持. 缺点: ...

  9. 纯JS实现俄罗斯方块,打造属于你的游戏帝国

    纯JS俄罗斯方块,打造属于你的游戏帝国. 本文原始作者博客 http://www.cnblogs.com/toutou 俄罗斯方块(Tetris, 俄文:Тетрис)是一款电视游戏机和掌上游戏机游戏 ...

  10. 1、SQL Server自动化运维 - 备份(一)业务数据库

    为了能够恢复数据,数据库运维基础就是备份,备份自动化也是运维自动化首要进行的. 笔者的备份自动化,通过配置表快速配置为前提,同时记录备份过程,尽可能的减少人工操作.首先将SQL Server备份按用途 ...