Redis笔记(七)Java实现Redis消息队列
这里我使用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();
}
}
Redis笔记(七)Java实现Redis消息队列的更多相关文章
- 手把手教你用redis实现一个简单的mq消息队列(java)
众所周知,消息队列是应用系统中重要的组件,主要解决应用解耦,异步消息,流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构.目前使用较多的消息队列有 ActiveMQ,RabbitMQ,Zero ...
- Java分布式:消息队列(Message Queue)
Java分布式:消息队列(Message Queue) 引入消息队列 消息,是服务间通信的一种数据单位,消息可以非常简单,例如只包含文本字符串:也可以更复杂,可能包含嵌入对象.队列,是一种常见的数据结 ...
- Java高并发--消息队列
Java高并发--消息队列 主要是学习慕课网实战视频<Java并发编程入门与高并发面试>的笔记 举个例子:在购物商城下单后,希望购买者能收到短信或者邮件通知.有一种做法时在下单逻辑执行后调 ...
- 【MQ】java 从零开始实现消息队列 mq-02-如何实现生产者调用消费者?
前景回顾 上一节我们学习了如何实现基于 netty 客服端和服务端的启动. [mq]从零开始实现 mq-01-生产者.消费者启动 [mq]java 从零开始实现消息队列 mq-02-如何实现生产者调用 ...
- Redis 竟然能用 List 实现消息队列
分布式系统中必备的一个中间件就是消息队列,通过消息队列我们能对服务间进行异步解耦.流量消峰.实现最终一致性. 目前市面上已经有 RabbitMQ.RochetMQ.ActiveMQ.Kafka等,有人 ...
- redis k-v数据库、高速缓存、消息队列代理
Redis 简介 Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库. Redis 与其他 key - value 缓存产品有以下三个特点: Redis支持数据的 ...
- Redis笔记(六)Redis的消息通知
Redis的消息通知可以使用List类型的LPUSH和RPOP(左进右出),当然更方便的是直接使用Redis的Pub/Sub(发布/订阅)模式. >>使用List实现队列 使用列表类型的L ...
- 使用redis的发布订阅模式实现消息队列
配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://w ...
- Redis中的Stream数据类型作为消息队列的尝试
Redis的List数据类型作为消息队列,已经比较合适了,但存在一些不足,比如只能独立消费,订阅发布又无法支持数据的持久化,相对前两者,Redis Stream作为消息队列的使用更为有优势. 相信 ...
- Redis系列(五):消息队列
消息队列已经成为现在互联网服务端的标配组件,现在比较常用的消息中间件有RabbitMQ.Kafka.RocketMQ.ActiveMQ.说出来你可能不信,Redis作为一个缓存中间件,居然也提供了消息 ...
随机推荐
- html5的触摸事件
1.触摸事件有哪些 touchstart,touchmove,touchend 2.分别什么时候触发 touchstart事件:当手指触摸屏幕时候触发,即使已经有一个手指放在屏幕上也会触发. touc ...
- python del 注意点
>>> del a[:] >>> a [] del也可以用于删除整个变量: >>> >>> del a 之后再引用名称 a 将会 ...
- Linux环境变量的添加设置
以前一直都记着的,后来做的事情多了就什么都忘的差不多了. 在Linux中,环境变量一般添加有这么几个地方: 1./etc/profile 这个目录设置的变量为整个系统的全局变量,所有的用户通用,一般不 ...
- 17.4---返回max,不用if
思路:借助max公式就可以了.max(x,y)=0.5*(x+y+|x-y|) 注意:1,结尾要加(int). 答案: max(x,y)=0.5*(x+y+|x-y|)
- wordpress迁移到本地404错误
线上wordpress迁移到本地可能出现找不到页面问题,可能是因为配置了url静态化,同时wordpress的文章链接是存在数据库中的 下面替换掉原来线上的文章链接,其中数据库名为wordpress ...
- ubuntu14.04 163sources.list
deb http://mirrors.163.com/ubuntu/ trusty main restricted universe multiverse deb http://mirrors.163 ...
- C# nullable<T> 用法小结
今天在园子里看到一个关于C#中对于可空类型的描述的帖子,感觉不错于是自己写了个小例子尝试下. 在C#中,对于可空类型描述为:Nullable<T>, 它表示该类型是可以为空的一个类型.它被 ...
- struts2 模型驱动
public class User3Action extends ActionSupport implements ModelDriven<User> { private User use ...
- 在win7-64bit环境下,boa-constructor 0.6.1 的palette面板中没有控件图标的解决方法
在win7-64bit环境下,boa-constructor 0.6.1 的palette面板中没有控件图标,空白一片.将面板窗口拉大,发现那些图标在很下面的位置,X轴的排列与正常状态一致. 软件环境 ...
- java切换VPN让你像幽灵一样出现在全国各地
在很多情况下,有些网络应用的需求会要求模拟人在不同地区访问网站和应用.因而切换IP也就应运而生了,然而IP作为一种稀缺资源不是随便可以获得的.因而会想到应用程序切换VPN来达到全国不同地区访问网络.因 ...