Redis实现消息队列的模式
常用的消息队列有RabbitMQ, ActiveMQ, Kafka等,这都是开源的功能强大的消息队列,适合于在企业项目应用。
Redis实现的消息队列代码原理
Redis提供了两种方式来作消息队列。
一个是使用生产者消费模式模式,
另一个就是发布订阅者模式。
前者会让一个或者多个客户端监听消息队列,一旦消息到达,消费者马上消费,谁先抢到算谁的,如果队列里没有消息,则消费者继续监听。
后者也是一个或多个客户端订阅消息频道,只要发布者发布消息,所有订阅者都能收到消息,订阅者都是平等的。
本文采用的是生产者消费者模式。
基于Redis的消息队列实现的异步操作原理图如下:
EventProducer将事件推送到消息队列中,
EventConsumer监听队列,只要监测到有事件到达,就将事件取出,交给对应的Handler进行处理。
代码实现
1. Redis数据库的底层操作:
将事件序列化后存入数据库;从数据库获取事件:
package com.wgs.mailSender.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.List;
/**
* Created by wanggenshen_sx on 2017/5/9.
*/
Service
public class JedisAdapter implements InitializingBean{
private static final Logger logger = LoggerFactory.getLogger(JedisAdapter.class);
private Jedis jedis = null;
private JedisPool jedisPool = null;
/**
* 初始化
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
jedisPool = new JedisPool("localhost", 6379);
}
/**
* 从JedisPool获取一个Jedis连接
* @return
*/
private Jedis getJedis(){
try {
jedis = jedisPool.getResource();
return jedis;
}catch (Exception e){
logger.error("获取Jedis 异常 :" + e.getMessage());
return null;
}finally {
if (jedis != null){
try {
jedis.close();
}catch (Exception e){
logger.error(e.getMessage());
}
}
}
}
/**
* 存入List集合中
* @param key
* @param value
* @return
*/
public long lpush(String key, String value){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
long result = jedis.lpush(key, value);
return result;
}catch (Exception e){
logger.error("Jedis lpush 异常 :" + e.getMessage());
return 0;
}finally {
if (jedis != null){
try {
jedis.close();
}catch (Exception e){
logger.error(e.getMessage());
}
}
}
}
/**
* 获取指定值
* @param timeout
* @param key
* @return
*/
public List<String> brpop(int timeout, String key){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.brpop(timeout, key);
}catch (Exception e){
logger.error("Jedis brpop 异常 :" + e.getMessage());
return null;
}finally {
if (jedis != null){
try {
jedis.close();
}catch (Exception e){
logger.error(e.getMessage());
}
}
}
}
/**
* 给Redis中Set集合中某个key值设值
* @param key
* @param value
*/
public void set(String key, String value){
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set(key, value);
}catch (Exception e){
logger.error("Jedis set 异常" + e.getMessage());
}