SpringBoot2.0 整合 Redis集群 ,实现消息队列场景
本文源码
GitHub地址:知了一笑
https://github.com/cicadasmile/middle-ware-parent
一、Redis集群简介
1、RedisCluster概念
Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的需求,当一个服务宕机可以快速的切换到另外一个服务。redis cluster主要是针对海量数据+高并发+高可用的场景。
二、与SpringBoot2.0整合
1、核心依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>${spring-boot.version}</version>
</dependency>
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>${redis-client.version}</version>
</dependency>
2、核心配置
spring:# Redis 集群redis:sentinel:# sentinel 配置master: mymasternodes: 192.168.0.127:26379maxTotal: 60minIdle: 10maxWaitMillis: 10000testWhileIdle: truetestOnBorrow: truetestOnReturn: falsetimeBetweenEvictionRunsMillis: 10000
3、参数渲染类
@ConfigurationProperties(prefix = "spring.redis.sentinel")
public class RedisParam {private String nodes ;private String master ;private Integer maxTotal ;private Integer minIdle ;private Integer maxWaitMillis ;private Integer timeBetweenEvictionRunsMillis ;private boolean testWhileIdle ;private boolean testOnBorrow ;private boolean testOnReturn ;// 省略GET和SET方法
}
4、集群配置文件
@Configuration
@EnableConfigurationProperties(RedisParam.class)
public class RedisPool {@Resourceprivate RedisParam redisParam ;@Bean("jedisSentinelPool")public JedisSentinelPool getRedisPool (){Set<String> sentinels = new HashSet<>();sentinels.addAll(Arrays.asList(redisParam.getNodes().split(",")));GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();poolConfig.setMaxTotal(redisParam.getMaxTotal());poolConfig.setMinIdle(redisParam.getMinIdle());poolConfig.setMaxWaitMillis(redisParam.getMaxWaitMillis());poolConfig.setTestWhileIdle(redisParam.isTestWhileIdle());poolConfig.setTestOnBorrow(redisParam.isTestOnBorrow());poolConfig.setTestOnReturn(redisParam.isTestOnReturn());poolConfig.setTimeBetweenEvictionRunsMillis(redisParam.getTimeBetweenEvictionRunsMillis());JedisSentinelPool redisPool = new JedisSentinelPool(redisParam.getMaster(), sentinels, poolConfig);return redisPool;}@BeanSpringUtil springUtil() {return new SpringUtil();}@BeanRedisListener redisListener() {return new RedisListener();}
}
5、配置Redis模板类
@Configuration
public class RedisConfig {@Beanpublic StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();stringRedisTemplate.setConnectionFactory(factory);return stringRedisTemplate;}
}
三、模拟队列场景案例
生产者消费者模式:客户端监听消息队列,消息达到,消费者马上消费,如果消息队列里面没有消息,那么消费者就继续监听。基于Redis的LPUSH(BLPUSH)把消息入队,用 RPOP(BRPOP)获取消息的模式。
1、加锁解锁工具
@Component
public class RedisLock {private static String keyPrefix = "RedisLock:";@Resourceprivate JedisSentinelPool jedisSentinelPool;public boolean addLock(String key, long expire) {Jedis jedis = null;try {jedis = jedisSentinelPool.getResource();/** nxxx的值只能取NX或者XX,如果取NX,则只有当key不存在是才进行set,如果取XX,则只有当key已经存在时才进行set* expx的值只能取EX或者PX,代表数据过期时间的单位,EX代表秒,PX代表毫秒。*/String value = jedis.set(keyPrefix + key, "1", "nx", "ex", expire);return value != null;} catch (Exception e){e.printStackTrace();}finally {if (jedis != null) jedis.close();}return false;}public void removeLock(String key) {Jedis jedis = null;try {jedis = jedisSentinelPool.getResource();jedis.del(keyPrefix + key);} finally {if (jedis != null) jedis.close();}}
}
2、消息消费
1)封装接口
public interface RedisHandler {/*** 队列名称*/String queueName();/*** 队列消息内容*/String consume (String msgBody);
}
2)接口实现
@Component
public class LogAListen implements RedisHandler {private static final Logger LOG = LoggerFactory.getLogger(LogAListen.class) ;@Resourceprivate RedisLock redisLock;@Overridepublic String queueName() {return "LogA-key";}@Overridepublic String consume(String msgBody) {// 加锁,防止消息重复投递String lockKey = "lock-order-uuid-A";boolean lock = false;try {lock = redisLock.addLock(lockKey, 60);if (!lock) {return "success";}LOG.info("LogA-key == >>" + msgBody);} catch (Exception e){e.printStackTrace();} finally {if (lock) {redisLock.removeLock(lockKey);}}return "success";}
}
3、消息监听器
public class RedisListener implements InitializingBean {/*** Redis 集群*/@Resourceprivate JedisSentinelPool jedisSentinelPool;private List<RedisHandler> handlers = null;private ExecutorService product = null;private ExecutorService consumer = null;/*** 初始化配置*/@Overridepublic void afterPropertiesSet() {handlers = SpringUtil.getBeans(RedisHandler.class) ;product = new ThreadPoolExecutor(10,15,60 * 3,TimeUnit.SECONDS,new SynchronousQueue<>());consumer = new ThreadPoolExecutor(10,15,60 * 3,TimeUnit.SECONDS,new SynchronousQueue<>());for (RedisHandler redisHandler : handlers){product.execute(() -> {redisTask(redisHandler);});}}/*** 队列监听*/public void redisTask (RedisHandler redisHandler){Jedis jedis = null ;while (true){try {jedis = jedisSentinelPool.getResource() ;List<String> msgBodyList = jedis.brpop(0, redisHandler.queueName());if (msgBodyList != null && msgBodyList.size()>0){consumer.execute(() -> {redisHandler.consume(msgBodyList.get(1)) ;});}} catch (Exception e){e.printStackTrace();} finally {if (jedis != null) jedis.close();}}}
}
4、消息生产者
@Service
public class RedisServiceImpl implements RedisService {@Resourceprivate JedisSentinelPool jedisSentinelPool;@Overridepublic void saveQueue(String queueKey, String msgBody) {Jedis jedis = null;try {jedis = jedisSentinelPool.getResource();jedis.lpush(queueKey,msgBody) ;} catch (Exception e){e.printStackTrace();} finally {if (jedis != null) jedis.close();}}
}
5、场景测试接口
@RestController
public class RedisController {@Resourceprivate RedisService redisService ;/*** 队列推消息*/@RequestMapping("/saveQueue")public String saveQueue (){MsgBody msgBody = new MsgBody() ;msgBody.setName("LogAModel");msgBody.setDesc("描述");msgBody.setCreateTime(new Date());redisService.saveQueue("LogA-key", JSONObject.toJSONString(msgBody));return "success" ;}
}
四、源代码地址
GitHub地址:知了一笑
https://github.com/cicadasmile/middle-ware-parent
码云地址:知了一笑
https://gitee.com/cicadasmile/middle-ware-parent
SpringBoot2.0 整合 Redis集群 ,实现消息队列场景相关推荐
- Pyspider 使用带认证redis集群作为消息队列
文章目录 概述 pyspider message_queue 源码解读 pyspider的message_queue的配置文件 使用redis集群时的配置文件 使用redis单点,带认证时的messa ...
- Springboot2.0访问Redis集群
Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作高性能的key-value数据库.缓存和消息中间件,掌握它是程序员的必备技能,下面是一个springboot访问redis的 ...
- springboot2.x 整合redis集群的几种方式
一.不指定redis连接池 #系统默认连接池 yml配置文件: spring:redis:cluster:nodes:- 192.168.1.236:7001- 192.168.1.236:7002- ...
- SpringBoot整合Redis集群版本问题
QUESTION:SpringBoot整合Redis集群版本问题? ANSWER: 版本依赖: <dependencies><!-- https://mvnrepository.co ...
- Springboot项目整合redis集群
文章目录 1.redis集群搭建 详情见: https://blog.csdn.net/qq_45076180/article/details/103026150 2.springboot整合redi ...
- java集群解析文件_java相关:springboot整合redis集群过程解析
java相关:springboot整合redis集群过程解析 发布于 2020-4-13| 复制链接 摘记: 简介 在springboot使用搭建好的redis集群添加redis和连接池依赖 ```x ...
- 超完整!Springboot整合redis集群(Sentine),spring boot自动配置集成redis集群(Sentine)
1.添加maven依赖 注意maven版本依赖,版本要相互匹配,如不知道如何查看相对应的版本时,可进入博主主页查看博主上一篇博文. <parent><groupId>org.s ...
- [由零开始]Spring boot 整合redis集群
Spring boot 整合redis集群 一.环境搭建 Redis集群环境搭建:https://blog.csdn.net/qq497811258/article/details/108124697 ...
- springboot篇】二十二. springboot整合Redis集群
springboot整合Redis集群 **中国加油,武汉加油!** 案例准备 1. 新建Springboot项目springboot-redis-sentinel 2. 编写yml 3. Test ...
最新文章
- Microsoft StreamInsight 构建物联网
- [Asp.net]使用flexpaper+swftools大文件分页转换实现在线预览
- 百度无人驾驶出租长沙开测:Apollo技术一汽红旗车队,年内服役
- 离职半年了,最近又开始被吐槽输出不够...
- python语言格式化输出_Python | 格式化输出字符串
- python以追加方式打开文件 线程安全吗,Python的open函数文件读写线程不安全,logging模型文件读写线程安全!...
- 使用@Configuration注解来代替Spring的bean配置
- PHP CLI应用的调试原理
- 仅需一行代码,你的纯文本秒变Markdown
- 论文浅尝 | Tree-to-sequence 学习知识问答
- “10%时间”:优点和缺点——敏捷海滩会议上Elizabeth Pope的报告
- Hey! 首先祝贺 SpaceX 发射成功,其次我黑了 NASA 某IT 承包商网络哟~
- 1.3 Linux存储技术
- ubuntu16.04 安装 wxPython方法
- elementui的横向滚动_记一次element-ui配置化table组件的适应性问题(横向滚动条)...
- 抖音店群玩法之后端维护
- linux生成4g文件,linux中创建超过4g文件的方法-o_largefile?
- SpringMVC整合activiti Modeler
- 智能电子快递面单系统
- 邂逅你,是我最美的相遇
热门文章
- 6-6-3:STL之map和set——multiset和multimap及set和map在oj题中的用处
- TCP/IP 免费ARP
- eclipse连接MySQL
- 作业要求 20171130 每周例行报告
- laravel CURD
- 修改文件中的内容,使用fileinput模块
- loaded the ViewController nib but the view outlet was not set. 处理方式
- hdu1242 Rescue DFS(路径探索题)
- 开源的C#组件——RSS.NET
- Javascript高级程序设计第二版第十一章--DOM2,DOM3--笔记