Spring-data-redis: 分布式队列
Redis中list数据结构,具有“双端队列”的特性,同时redis具有持久数据的能力,因此redis实现分布式队列是非常安全可靠的。它类似于JMS中的“Queue”,只不过功能和可靠性(事务性)并没有JMS严格。
Redis中的队列阻塞时,整个connection都无法继续进行其他操作,因此在基于连接池设计是需要注意。
我们通过spring-data-redis,来实现“同步队列”,设计风格类似与JMS。
一.配置文件:
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName">
- <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
- <property name="maxActive" value="32"></property>
- <property name="maxIdle" value="6"></property>
- <property name="maxWait" value="15000"></property>
- <property name="minEvictableIdleTimeMillis" value="300000"></property>
- <property name="numTestsPerEvictionRun" value="3"></property>
- <property name="timeBetweenEvictionRunsMillis" value="60000"></property>
- <property name="whenExhaustedAction" value="1"></property>
- </bean>
- <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
- <property name="poolConfig" ref="jedisPoolConfig"></property>
- <property name="hostName" value="127.0.0.1"></property>
- <property name="port" value="6379"></property>
- <property name="password" value="0123456"></property>
- <property name="timeout" value="15000"></property>
- <property name="usePool" value="true"></property>
- </bean>
- <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
- <property name="connectionFactory" ref="jedisConnectionFactory"></property>
- <property name="defaultSerializer">
- <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
- </property>
- </bean>
- <bean id="jedisQueueListener" class="com.sample.redis.sdr.QueueListener"/>
- <bean id="jedisQueue" class="com.sample.redis.sdr.RedisQueue" destroy-method="destroy">
- <property name="redisTemplate" ref="jedisTemplate"></property>
- <property name="key" value="user:queue"></property>
- <property name="listener" ref="jedisQueueListener"></property>
- </bean>
- </beans>
二.程序实例:
1) QueueListener:当队列中有数据时,可以执行类似于JMS的回调操作。
- public interface RedisQueueListener<T> {
- public void onMessage(T value);
- }
- public class QueueListener<String> implements RedisQueueListener<String> {
- @Override
- public void onMessage(String value) {
- System.out.println(value);
- }
- }
2) RedisQueue:队列操作,内部封装redisTemplate实例;如果配置了“listener”,那么queue将采用“消息回调”的方式执行,listenerThread是一个后台线程,用来自动处理“队列信息”。如果不配置“listener”,那么你可以将redisQueue注入到其他spring bean中,手动去“take”数据即可。
- public class RedisQueue<T> implements InitializingBean,DisposableBean{
- private RedisTemplate redisTemplate;
- private String key;
- private int cap = Short.MAX_VALUE;//最大阻塞的容量,超过容量将会导致清空旧数据
- private byte[] rawKey;
- private RedisConnectionFactory factory;
- private RedisConnection connection;//for blocking
- private BoundListOperations<String, T> listOperations;//noblocking
- private Lock lock = new ReentrantLock();//基于底层IO阻塞考虑
- private RedisQueueListener listener;//异步回调
- private Thread listenerThread;
- private boolean isClosed;
- public void setRedisTemplate(RedisTemplate redisTemplate) {
- this.redisTemplate = redisTemplate;
- }
- public void setListener(RedisQueueListener listener) {
- this.listener = listener;
- }
- public void setKey(String key) {
- this.key = key;
- }
- @Override
- public void afterPropertiesSet() throws Exception {
- factory = redisTemplate.getConnectionFactory();
- connection = RedisConnectionUtils.getConnection(factory);
- rawKey = redisTemplate.getKeySerializer().serialize(key);
- listOperations = redisTemplate.boundListOps(key);
- if(listener != null){
- listenerThread = new ListenerThread();
- listenerThread.setDaemon(true);
- listenerThread.start();
- }
- }
- /**
- * blocking
- * remove and get last item from queue:BRPOP
- * @return
- */
- public T takeFromTail(int timeout) throws InterruptedException{
- lock.lockInterruptibly();
- try{
- List<byte[]> results = connection.bRPop(timeout, rawKey);
- if(CollectionUtils.isEmpty(results)){
- return null;
- }
- return (T)redisTemplate.getValueSerializer().deserialize(results.get(1));
- }finally{
- lock.unlock();
- }
- }
- public T takeFromTail() throws InterruptedException{
- return takeFromHead(0);
- }
- /**
- * 从队列的头,插入
- */
- public void pushFromHead(T value){
- listOperations.leftPush(value);
- }
- public void pushFromTail(T value){
- listOperations.rightPush(value);
- }
- /**
- * noblocking
- * @return null if no item in queue
- */
- public T removeFromHead(){
- return listOperations.leftPop();
- }
- public T removeFromTail(){
- return listOperations.rightPop();
- }
- /**
- * blocking
- * remove and get first item from queue:BLPOP
- * @return
- */
- public T takeFromHead(int timeout) throws InterruptedException{
- lock.lockInterruptibly();
- try{
- List<byte[]> results = connection.bLPop(timeout, rawKey);
- if(CollectionUtils.isEmpty(results)){
- return null;
- }
- return (T)redisTemplate.getValueSerializer().deserialize(results.get(1));
- }finally{
- lock.unlock();
- }
- }
- public T takeFromHead() throws InterruptedException{
- return takeFromHead(0);
- }
- @Override
- public void destroy() throws Exception {
- if(isClosed){
- return;
- }
- shutdown();
- RedisConnectionUtils.releaseConnection(connection, factory);
- }
- private void shutdown(){
- try{
- listenerThread.interrupt();
- }catch(Exception e){
- //
- }
- }
- class ListenerThread extends Thread {
- @Override
- public void run(){
- try{
- while(true){
- T value = takeFromHead();//cast exceptionyou should check.
- //逐个执行
- if(value != null){
- try{
- listener.onMessage(value);
- }catch(Exception e){
- //
- }
- }
- }
- }catch(InterruptedException e){
- //
- }
- }
- }
- }
3) 使用与测试:
- public static void main(String[] args) throws Exception{
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-redis-beans.xml");
- RedisQueue<String> redisQueue = (RedisQueue)context.getBean("jedisQueue");
- redisQueue.pushFromHead("test:app");
- Thread.sleep(15000);
- redisQueue.pushFromHead("test:app");
- Thread.sleep(15000);
- redisQueue.destroy();
- }
在程序运行期间,你可以通过redis-cli(客户端窗口)执行“lpush”,你会发现程序的控制台仍然能够正常打印队列信息。
Spring-data-redis: 分布式队列的更多相关文章
- Spring Data Redis实现消息队列——发布/订阅模式
一般来说,消息队列有两种场景,一种是发布者订阅者模式,一种是生产者消费者模式.利用redis这两种场景的消息队列都能够实现. 定义:生产者消费者模式:生产者生产消息放到队列里,多个消费者同时监听队列, ...
- Spring Data Redis—Pub/Sub(附Web项目源码)
一.发布和订阅机制 当一个客户端通过 PUBLISH 命令向订阅者发送信息的时候,我们称这个客户端为发布者(publisher). 而当一个客户端使用 SUBSCRIBE 或者 PSUBSCRIBE ...
- Spring Data Redis—Pub/Sub(附Web项目源码) (转)
一.发布和订阅机制 当一个客户端通过 PUBLISH 命令向订阅者发送信息的时候,我们称这个客户端为发布者(publisher). 而当一个客户端使用 SUBSCRIBE 或者 PSUBSCRIBE ...
- Spring Data Redis 详解及实战一文搞定
SDR - Spring Data Redis的简称. Spring Data Redis提供了从Spring应用程序轻松配置和访问Redis的功能.它提供了与商店互动的低级别和高级别抽象,使用户免受 ...
- spring data redis RedisTemplate操作redis相关用法
http://blog.mkfree.com/posts/515835d1975a30cc561dc35d spring-data-redis API:http://docs.spring.io/sp ...
- spring mvc Spring Data Redis RedisTemplate [转]
http://maven.springframework.org/release/org/springframework/data/spring-data-redis/(spring-data包下载) ...
- Spring Data Redis简介以及项目Demo,RedisTemplate和 Serializer详解
一.概念简介: Redis: Redis是一款开源的Key-Value数据库,运行在内存中,由ANSI C编写,详细的信息在Redis官网上面有,因为我自己通过google等各种渠道去学习Redis, ...
- Spring data redis的一个bug
起因 前两天上线了一个新功能,导致线上业务的缓存总是无法更新,报错也是非常奇怪,redis.clients.jedis.exceptions.JedisConnectionException: Unk ...
- spring data redis 理解
前言 Spring Data Redis project,应用了Spring概念来开发使用键值形式的数据存储的解决方案.我们(官方)提供了一个 "template" ,这是一个高级 ...
- Spring Data Redis 让 NoSQL 快如闪电(2)
[编者按]本文作者为 Xinyu Liu,文章的第一部分重点概述了 Redis 方方面面的特性.在第二部分,将介绍详细的用例.文章系国内 ITOM 管理平台 OneAPM 编译呈现. 把 Redis ...
随机推荐
- XLSReadWrite控件简介
2015-10-22 23:57:55 原帖地址:http://www.cnblogs.com/dabiao/archive/2011/07/08/2100609.html XLSReadWrite ...
- Labview学习之程序Web发布
Labview学习之程序Web发布 1. LabVIEW Web服务器 在LabVIEW开发环境中,自身带了一个已连接好的Web服务器.LabVIEW Web服务器除了与其他Web服务器一样能 ...
- IE8,9下的ajax缓存问题
最近在做一个网站的登录注册框,前端使用了jquery.由于sign和login不是在单独的页面上,而是以一个弹出框出现.所以决定使用ajax来实现注册和登录功能.本以为可以一帆风顺,结果在测试的时候发 ...
- Python的maketrans() 方法
描述 Python maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标. 注:两个字符 ...
- SMT贴片红胶基本知识
SMT贴片红胶是一种聚稀化合物,与锡膏不同的是其受热后便固化,其凝固点温度为150℃,这时,红胶开始由膏状体直接变成固体. SMT贴片机装贴贴片具有粘度流动性,温度特性,润湿特性等.根据红胶的这个特性 ...
- JavaEE Tutorials (13) - 使用锁定控制对实体数据的并发访问
13.1实体锁定和并发概述180 13.1.1使用乐观锁定18113.2锁模式181 13.2.1设置锁模式182 13.2.2使用悲观锁定183
- VM 映像
让我们一起欢呼吧!随着最近Microsoft Azure运行时的发布,我们非常高兴地宣布发布 OS映像的继承性产品:新 VM映像.等一下-有些人可能会觉得这听起来有点耳熟.没错,一个月前在旧金山 ...
- HDU 5730 Shell Necklace(CDQ分治+FFT)
[题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=5730 [题目大意] 给出一个数组w,表示不同长度的字段的权值,比如w[3]=5表示如果字段长度为3 ...
- Extjs4 类的定义和扩展
一般定义方式,注意方法和函数的添加方式不同.(添加函数只能用override方式添加不知为什么,有知道的,请搞之.) 定义一个类,并给他一个方法 1: Ext.define('Simple.Class ...
- 基于SMTP协议的CMD命令邮件发送
网上有不少的这类的文章,以是参照这些文章后,自己实际运行的结果.系统使用的是WIN7 旗舰版. 1.打开CMD命令后,连接到SMTP服务器,如连接到QQ的SMTP服务,输入命令 telnet smtp ...