这里我使用Redis的发布、订阅功能实现简单的消息队列,基本的命令有publish、subscribe等。

在Jedis中,有对应的java方法,但是只能发布字符串消息。为了传输对象,需要将对象进行序列化,并封装成字符串进行处理。

使用Redis实现消息队列


封装一个消息对象

public class Message implements Serializable{

private static final long serialVersionUID = 1L;

private String titile;
private String info; public Message(String titile,String info){
this.titile=titile;
this.info=info;
} public String getTitile() {
return titile;
}
public void setTitile(String titile) {
this.titile = titile;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}

  

为这个消息对象提供序列化方法

public class MessageUtil {

//convert To String
public static String convertToString(Object obj,String charset) throws IOException{ ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
String str = bo.toString(charset);
bo.close();
oo.close();
return str;
} //convert To Message
public static Object convertToMessage(byte[] bytes) throws Exception{
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream sIn = new ObjectInputStream(in);
return sIn.readObject(); }
}

  

从Jedis连接池中获取连接

public class RedisUtil {

/**
* Jedis connection pool
* @Title: config
*/
public static JedisPool getJedisPool(){
ResourceBundle bundle=ResourceBundle.getBundle("redis");
String host=bundle.getString("host");
int port=Integer.valueOf(bundle.getString("port"));
int timeout=Integer.valueOf(bundle.getString("timeout"));
// String password=bundle.getString("password"); JedisPoolConfig config=new JedisPoolConfig();
config.setMaxActive(Integer.valueOf(bundle.getString("maxActive")));
config.setMaxWait(Integer.valueOf(bundle.getString("maxWait")));
config.setTestOnBorrow(Boolean.valueOf(bundle.getString("testOnBorrow")));
config.setTestOnReturn(Boolean.valueOf(bundle.getString("testOnReturn"))); JedisPool pool=new JedisPool(config, host, port, timeout); return pool;
}
}

  

创建Provider类

public class Producer {

private Jedis jedis;
private JedisPool pool; public Producer(){
pool=RedisUtil.getJedisPool();
jedis = pool.getResource();
} public void provide(String channel,Message message) throws IOException{
String str1=MessageUtil.convertToString(channel,"UTF-8");
String str2=MessageUtil.convertToString(message,"UTF-8");
jedis.publish(str1, str2);
} //close the connection
public void close() throws IOException {
//将Jedis对象归还给连接池,关闭连接
pool.returnResource(jedis);
}
}

  

创建Consumer类

public class Consumer {

private Jedis jedis;
private JedisPool pool; public Consumer(){
pool=RedisUtil.getJedisPool();
jedis = pool.getResource();
} public void consum(String channel) throws IOException{
JedisPubSub jedisPubSub = new JedisPubSub() {
// 取得订阅的消息后的处理
public void onMessage(String channel, String message) {
System.out.println("Channel:"+channel);
System.out.println("Message:"+message.toString());
} // 初始化订阅时候的处理
public void onSubscribe(String channel, int subscribedChannels) {
System.out.println("onSubscribe:"+channel);
} // 取消订阅时候的处理
public void onUnsubscribe(String channel, int subscribedChannels) {
System.out.println("onUnsubscribe:"+channel);
} // 初始化按表达式的方式订阅时候的处理
public void onPSubscribe(String pattern, int subscribedChannels) {
// System.out.println(pattern + "=" + subscribedChannels);
} // 取消按表达式的方式订阅时候的处理
public void onPUnsubscribe(String pattern, int subscribedChannels) {
// System.out.println(pattern + "=" + subscribedChannels);
} // 取得按表达式的方式订阅的消息后的处理
public void onPMessage(String pattern, String channel, String message) {
System.out.println(pattern + "=" + channel + "=" + message);
}
}; jedis.subscribe(jedisPubSub, channel);
} //close the connection
public void close() throws IOException {
//将Jedis对象归还给连接池
pool.returnResource(jedis);
}
}

  

测试方法

public static void main(String[] args){

Message msg=new Message("hello!", "this is the first message!");

Producer producer=new Producer();
Consumer consumer=new Consumer();
try {
producer.provide("chn1",msg);
consumer.consum("chn1");
} catch (IOException e) {
e.printStackTrace();
}
}

  

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

  1. Redis笔记(七)Java实现Redis消息队列

    这里我使用Redis的发布.订阅功能实现简单的消息队列,基本的命令有publish.subscribe等. 在Jedis中,有对应的java方法,但是只能发布字符串消息.为了传输对象,需要将对象进行序 ...

  2. 预热一下吧《实现Redis消息队列》

    应用场景 为什么要用redis?二进制存储.java序列化传输.IO连接数高.连接频繁 一.序列化 这里编写了一个java序列化的工具,主要是将对象转化为byte数组,和根据byte数组反序列化成ja ...

  3. Java分布式:消息队列(Message Queue)

    Java分布式:消息队列(Message Queue) 引入消息队列 消息,是服务间通信的一种数据单位,消息可以非常简单,例如只包含文本字符串:也可以更复杂,可能包含嵌入对象.队列,是一种常见的数据结 ...

  4. java-spring基于redis单机版(redisTemplate)实现的分布式锁+redis消息队列,可用于秒杀,定时器,高并发,抢购

    此教程不涉及整合spring整合redis,可另行查阅资料教程. 代码: RedisLock package com.cashloan.analytics.utils; import org.slf4 ...

  5. redis消息队列简单应用

    消息队列出现的原因 随着互联网的高速发展,门户网站.视频直播.电商领域等web应用中,高并发.大数据已经成为基本的标识.淘宝双11.京东618.各种抢购.秒杀活动.以及12306的春运抢票等,他们这些 ...

  6. logstash解耦之redis消息队列

    logstash解耦之redis消息队列 架构图如下: 说明:通过input收集日志消息放入消息队列服务中(redis,MSMQ.Resque.ActiveMQ,RabbitMQ),再通过output ...

  7. Java高并发--消息队列

    Java高并发--消息队列 主要是学习慕课网实战视频<Java并发编程入门与高并发面试>的笔记 举个例子:在购物商城下单后,希望购买者能收到短信或者邮件通知.有一种做法时在下单逻辑执行后调 ...

  8. Redis 消息队列的实现

    概述 Redis实现消息队列有两种形式: 广播订阅模式:基于Redis的 Pub/Sub 机制,一旦有客户端往某个key里面 publish一个消息,所有subscribe的客户端都会触发事件 集群订 ...

  9. 【MQ】java 从零开始实现消息队列 mq-02-如何实现生产者调用消费者?

    前景回顾 上一节我们学习了如何实现基于 netty 客服端和服务端的启动. [mq]从零开始实现 mq-01-生产者.消费者启动 [mq]java 从零开始实现消息队列 mq-02-如何实现生产者调用 ...

随机推荐

  1. python3+selenium入门16-窗口截图

    有时候需要把一些浏览器当前窗口截图下来,比如操作抱错的时候.WebDriver类下.get_screenshot_as_file()方法可窗口截图,需要传入一个截图文件名的路径.window要用\\当 ...

  2. C++ URLencode library

    I need a library that can URLencode a string/char array. Now, I can hex encode an ASCII array like h ...

  3. js和thinkphp5路由拼接一个实例

    $.ajax({ type:"get", dataType:"json", url:"/home/index/ajax_page_data/cate_ ...

  4. 转-4年!我对OpenStack运维架构的总结

    4年!我对OpenStack运维架构的总结 原创: 徐超 云技术之家 今天 前言 应“云技术社区”北极熊之邀,写点东西.思来想去云计算范畴实在广泛,自然就聊点最近话题异常火热,让广大云计算从业者爱之深 ...

  5. 007_zkCli.sh

    一. [zk: localhost:2181(CONNECTED) 1] rmr /zkTestPaths_92018-06-25 11:18:30,189 [myid:] - WARN [main- ...

  6. [转]golang中defer的使用规则

    转载于:https://studygolang.com/articles/10167 在golang当中,defer代码块会在函数调用链表中增加一个函数调用.这个函数调用不是普通的函数调用,而是会在函 ...

  7. C#获取当前主机硬件信息

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  8. Ubuntu16.04安装Maven3.5.4

      本篇教程在示例步骤中使用了以下版本的软件.操作时,请您以实际软件版本为准. 操作系统:Ubuntu 16.04.3 LTS Maven 版本:Apache Maven 3.5.4 JDK 版本:J ...

  9. 使用open live writer客户端写博客

    注:Windows Live Writer 已经停止更新,建议安装 Open Live Writer,下载地址: http://openlivewriter.org/ 使用open live writ ...

  10. Confluence 6 配置管理员会话安全的备注

    禁用密码确定. Confluence 安装使用自定义授权机制有可能会在密码校验的时候遇到问题.如果必要的话,你可以设置 password.confirmation.disabled 系统属性来禁用密码 ...