热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

深入解析Java如何利用Redis实现高效消息队列

本篇文章主要介绍了Java利用Redis实现消息队列的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧本文介绍了Java利用Redis实现消息队

本篇文章主要介绍了Java利用Redis实现消息队列的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

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

应用场景

为什么要用redis?

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

一、序列化

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

其代码如下:

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(); }}

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

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; }}

三、Redis的操作

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

结合队列的特点:

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

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

上代码:

package Utils;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;import java.util.List;import java.util.Map;import java.util.Set;/** * Created by Kinglf on 2016/10/17. */public class JedisUtil { private static String JEDIS_IP; private static int JEDIS_PORT; private static String JEDIS_PASSWORD; private static JedisPool jedisPool; static {  //Configuration自行写的配置文件解析类,继承自Properties  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);  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){   jedisPool.returnBrokenResource(jedis);   e.printStackTrace();  }finally {   close(jedis);  }  return value; } private static void close(Jedis jedis) {  try{   jedisPool.returnResource(jedis);  }catch (Exception e){   if(jedis.isConnected()){    jedis.quit();    jedis.disconnect();   }  } } 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 key reids键名  * @param 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 key reids键名  * @param 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 key reids键名  * @param destination 键值  */ 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 key 键名  * @return  */ public static List lpopList(byte[] key) {  List 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 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 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 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 hmget(Object key, String... fields) {  List 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 hkeys(String key) {  Set 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 lrange(byte[] key, int from, int to) {  List 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 hgetAll(byte[] key) {  Map result = null;  Jedis jedis = null;  try {   jedis = jedisPool.getResource();   result = jedis.hgetAll(key);  } catch (Exception e) {   //释放redis对象   jed本文来源gaodai$ma#com搞$$代**码网isPool.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 Utils;import java.io.IOException;import java.io.InputStream;import java.util.Properties;/** * Created by Kinglf on 2016/10/17. */public class Configuration extends Properties { private static final long serialVersiOnUID= -2296275030489943706L; 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 ioe) {  } }}

五、测试

import Model.Message;import Utils.JedisUtil;import Utils.ObjectUtil;import redis.clients.jedis.Jedis;import java.io.IOException;/** * Created by Kinglf on 2016/10/17. */public class TestRedisQueue { public static byte[] redisKey = "key".getBytes(); static {  try {   init();  } catch (IOException e) {   e.printStackTrace();  } } private static void init() throws IOException {  for (int i = 0; i <1000000; i++) {   Message message = new Message(i, "这是第" + i + "个内容");   JedisUtil.lpush(redisKey, ObjectUtil.object2Bytes(message));  } } public static void main(String[] args) {  try {   pop();  } catch (Exception e) {   e.printStackTrace();  } } private static void pop() throws Exception {  byte[] bytes = JedisUtil.rpop(redisKey);  Message msg = (Message) ObjectUtil.bytes2Object(bytes);  if (msg != null) {   System.out.println(msg.getId() + "----" + msg.getContent());  } }}

每执行一次pop()方法,结果如下:
1----这是第1个内容
2----这是第2个内容
3----这是第3个内容
4----这是第4个内容

总结

至此,整个Redis消息队列的生产者和消费者代码已经完成

1.Message 需要传送的实体类(需实现Serializable接口)

2.Configuration Redis的配置读取类,继承自Properties

3.ObjectUtil 将对象和byte数组双向转换的工具类

4.Jedis 通过消息队列的先进先出(FIFO)的特点结合Redis的list中的push和pop操作进行封装的工具类

以上就是Java如何使用Redis来实现消息队列的具体分析的详细内容,更多请关注gaodaima其它相关文章!



推荐阅读
  • 从 .NET 转 Java 的自学之路:IO 流基础篇
    本文详细介绍了 Java 中的 IO 流,包括字节流和字符流的基本概念及其操作方式。探讨了如何处理不同类型的文件数据,并结合编码机制确保字符数据的正确读写。同时,文中还涵盖了装饰设计模式的应用,以及多种常见的 IO 操作实例。 ... [详细]
  • 本文介绍如何使用阿里云的fastjson库解析包含时间戳、IP地址和参数等信息的JSON格式文本,并进行数据处理和保存。 ... [详细]
  • 本文深入探讨了HTTP请求和响应对象的使用,详细介绍了如何通过响应对象向客户端发送数据、处理中文乱码问题以及常见的HTTP状态码。此外,还涵盖了文件下载、请求重定向、请求转发等高级功能。 ... [详细]
  • 本文详细探讨了HTML表单中GET和POST请求的区别,包括它们的工作原理、数据传输方式、安全性及适用场景。同时,通过实例展示了如何在Servlet中处理这两种请求。 ... [详细]
  • 本文详细介绍了Java中org.neo4j.helpers.collection.Iterators.single()方法的功能、使用场景及代码示例,帮助开发者更好地理解和应用该方法。 ... [详细]
  • 本文详细解析了Python中的os和sys模块,介绍了它们的功能、常用方法及其在实际编程中的应用。 ... [详细]
  • 本题探讨如何通过最大流算法解决农场排水系统的设计问题。题目要求计算从水源点到汇合点的最大水流速率,使用经典的EK(Edmonds-Karp)和Dinic算法进行求解。 ... [详细]
  • 不确定性|放入_华为机试题 HJ9提取不重复的整数
    不确定性|放入_华为机试题 HJ9提取不重复的整数 ... [详细]
  • 对象自省自省在计算机编程领域里,是指在运行时判断一个对象的类型和能力。dir能够返回一个列表,列举了一个对象所拥有的属性和方法。my_list[ ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • VPX611是北京青翼科技推出的一款采用6U VPX架构的高性能数据存储板。该板卡搭载两片Xilinx Kintex-7系列FPGA作为主控单元,内置RAID控制器,支持多达8个mSATA盘,最大存储容量可达8TB,持续写入带宽高达3.2GB/s。 ... [详细]
  • 本文详细介绍了Java中的输入输出(IO)流,包括其基本概念、分类及应用。IO流是用于在程序和外部资源之间传输数据的一套API。根据数据流动的方向,可以分为输入流(从外部流向程序)和输出流(从程序流向外部)。此外,还涵盖了字节流和字符流的区别及其具体实现。 ... [详细]
  • 开发笔记:2020 BJDCTF Re encode
    开发笔记:2020 BJDCTF Re encode ... [详细]
  • 在软件开发过程中,MD5加密是一种常见的数据保护手段。本文将详细介绍如何在C#中使用两种不同的方式来实现MD5加密:字符串加密和流加密。 ... [详细]
  • 深入解析Redis内存对象模型
    本文详细介绍了Redis内存对象模型的关键知识点,包括内存统计、内存分配、数据存储细节及优化策略。通过实际案例和专业分析,帮助读者全面理解Redis内存管理机制。 ... [详细]
author-avatar
求道金林
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有