应用场景

  • 为什么要用redis?
    二进制存储、java序列化传输、IO连接数高、连接频繁

一、序列化

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

 1 package Utils;
2 import java.io.*;
3 /**
4 * Created by Kinglf on 2016/10/17.
5 */
6 public class ObjectUtil {
7 /**
8 * 对象转byte[]
9 * @param obj
10 * @return
11 * @throws IOException
12 */
13 public static byte[] object2Bytes(Object obj) throws IOException{
14 ByteArrayOutputStream bo=new ByteArrayOutputStream();
15 ObjectOutputStream oo=new ObjectOutputStream(bo);
16 oo.writeObject(obj);
17 byte[] bytes=bo.toByteArray();
18 bo.close();
19 oo.close();
20 return bytes;
21 }
22 /**
23 * byte[]转对象
24 * @param bytes
25 * @return
26 * @throws Exception
27 */
28 public static Object bytes2Object(byte[] bytes) throws Exception{
29 ByteArrayInputStream in=new ByteArrayInputStream(bytes);
30 ObjectInputStream sIn=new ObjectInputStream(in);
31 return sIn.readObject();
32 }
33 }

二、消息类(实现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对象
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 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()方法,结果如下:
<br>1----这是第1个内容
<br>2----这是第2个内容
<br>3----这是第3个内容
<br>4----这是第4个内容

总结

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

  1. Message 需要传送的实体类(需实现Serializable接口)
  2. Configuration Redis的配置读取类,继承自Properties
  3. ObjectUtil 将对象和byte数组双向转换的工具类
  4. Jedis 通过消息队列的先进先出(FIFO)的特点结合Redis的list中的push和pop操作进行封装的工具类

Java利用Redis实现消息队列的更多相关文章

  1. Springboot21 整合redis、利用redis实现消息队列

    1 前提准备 1.1 创建一个springboot项目 技巧01:本博文基于springboot2.0创建 1.2 安装redis 1.2.1 linux版本 参考博文 1.2.2 windows版本 ...

  2. 利用redis制作消息队列

    redis在游戏服务器中的使用初探(一) 环境搭建redis在游戏服务器中的使用初探(二) 客户端开源库选择redis在游戏服务器中的使用初探(三) 信息存储redis在游戏服务器中的使用初探(四) ...

  3. PHP中利用redis实现消息队列处理高并发请求

    将请求存入redis 为了模拟多个用户的请求,使用一个for循环替代 //redis数据入队操作 $redis = new Redis(); $redis->connect('127.0.0.1 ...

  4. Redis 做消息队列

    一般来说,消息队列有两种场景,一种是发布者订阅者模式,一种是生产者消费者模式.利用redis这两种场景的消息队列都能够实现.定义: 生产者消费者模式:生产者生产消息放到队列里,多个消费者同时监听队列, ...

  5. Redis除了做缓存--Redis做消息队列/Redis做分布式锁/Redis做接口限流

    1.用Redis实现消息队列 用命令lpush入队,rpop出队 Long size = jedis.lpush("QueueName", message);//返回存放的数据条数 ...

  6. Lumen开发:结合Redis实现消息队列(1)

    1.简介 Lumen队列服务为各种不同的后台队列提供了统一的API.队列允许你推迟耗时任务(例如发送邮件)的执行,从而大幅提高web请求速度. 1.1 配置 .env文件的QUEUE_DRIVER选项 ...

  7. 程序员过关斩将--redis做消息队列,香吗?

    Redis消息队列 在程序员这个圈子打拼了太多年,见过太多的程序员使用redis,其中一部分喜欢把redis做缓存(cache)使用,其中最典型的当属存储用户session,除此之外,把redis作为 ...

  8. Redis作为消息队列服务场景应用案例

    NoSQL初探之人人都爱Redis:(3)使用Redis作为消息队列服务场景应用案例   一.消息队列场景简介 “消息”是在两台计算机间传送的数据单位.消息可以非常简单,例如只包含文本字符串:也可以更 ...

  9. redis resque消息队列

    Resque 目前正在学习使用resque .resque-scheduler来发布异步任务和定时任务,为了方便以后查阅,所以记录一下. resque和resque-scheduler其优点在于功能比 ...

随机推荐

  1. JAX-WS搭建WebService和客户端访问程序

    开发环境:myeclipse8.6+jdk1.6.0_29+tomcat6.0.37 XFire搭建webservice: http://www.cnblogs.com/gavinYang/p/352 ...

  2. NOIP2013 提高组 Day2

    期望得分:100+100+30+=230+ 实际得分:100+70+30=200 T2 觉得题目描述有歧义: 若存在2i却不存在2i+1,自己按不合法做的,实际是合法的 T3  bfs 难以估分 虽然 ...

  3. [Luogu 2486] SDOI2011 染色

    [Luogu 2486] SDOI2011 染色 树剖水题,线段树维护. 详细题解不写了. 我只想说我写的线段树又变漂亮了qwq #include <algorithm> #include ...

  4. c# WebService SOAP及Rest调用

    SOAP及Rest的调用区别参照如下: REST似乎在一夜间兴起了,这可能引起一些争议,反对者可以说REST是WEB诞生之始甚而是HTTP出现之日就相伴而生的原则.但是毋庸置疑的事实是,在Google ...

  5. js、php本周第一天和本周最后一天

    PHP:本周一 echo date('Y-m-d',(time()-((date('w')==0?7:date('w'))-1)*24*3600)); //w为星期几的数字形式,这里0为周日 本周日 ...

  6. phpcms添加子栏目后的读取

    一个栏目下面如果没有子栏目,那么它调用的模板就是列表页模板(及list_为前缀的模板):如果一个栏目下面有子栏目,那么它调用的就是栏目首页模板(category_为前缀的模板). 所以,当你这个栏目添 ...

  7. vue--------脚手架vue-cli搭建

    今天在看公司的项目的时候,用到的是Vue框架,哈哈,Vue已经火好久了,想必大家也晓得哈,这里宝宝就不瞎渣渣了~ 由于宝宝已经三个月木有看过代码了,所以对新公司的很多的架构和代码都是懵逼的,再加上宝宝 ...

  8. .net APIHelper client获取数据

    using Newtonsoft.Json; using System.Net.Http.Headers; public static class APIHepler { public static ...

  9. 游戏的物理和数学:Unity中的弹道和移动目标提前量计算

    下载地址:https://www.jianguoyun.com/p/DZPN6ocQ2siRBhihnx8 弹道计算是游戏里常见的问题,其中关于击中移动目标的自动计算提前量的话题,看似简单,其实还是挺 ...

  10. 【shell】shell编程(五)-读取参数

    通过前几篇文章的学习,我们学会了shell的基本语法.在linux的实际操作中,我们经常看到命令会有很多参数,例如:ls -al 等等,那么这个参数是怎么处理的呢? 接下来我们就来看看shell脚本对 ...