一、Redis集群简介

1、RedisCluster概念

Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的需求,当一个服务宕机可以快速的切换到另外一个服务。redis cluster主要是针对海量数据+高并发+高可用的场景。

2、Redis环境搭建

Linux系统:Centos7搭建Redis单台和集群环境

二、与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: mymaster
nodes: 192.168.0.127:26379
maxTotal: 60
minIdle: 10
maxWaitMillis: 10000
testWhileIdle: true
testOnBorrow: true
testOnReturn: false
timeBetweenEvictionRunsMillis: 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 {
@Resource
private 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;
}
@Bean
SpringUtil springUtil() {
return new SpringUtil();
}
@Bean
RedisListener redisListener() {
return new RedisListener();
}
}

5、配置Redis模板类

@Configuration
public class RedisConfig {
@Bean
public 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:";
@Resource
private 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) ;
@Resource
private RedisLock redisLock;
@Override
public String queueName() {
return "LogA-key";
}
@Override
public 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 集群
*/
@Resource
private JedisSentinelPool jedisSentinelPool;
private List<RedisHandler> handlers = null;
private ExecutorService product = null;
private ExecutorService consumer = null;
/**
* 初始化配置
*/
@Override
public 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 {
@Resource
private JedisSentinelPool jedisSentinelPool;
@Override
public 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 {
@Resource
private 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

原文发布于微信公众号 - 知了一笑(cicada_smile)

https://www.cnblogs.com/toutou/archive/2019/02/11/redis_lock.html

https://blog.csdn.net/u010199866/article/details/80705797

springboot11(springboot-redis)的更多相关文章

  1. Java商城秒杀系统的设计与实战视频教程(SpringBoot版)_汇总贴

    51CTO学院 Java商城秒杀系统的设计与实战视频教程(SpringBoot版) H:\BaiDu\微服务0830\2019最新 Java商城秒杀系统的设计与实战视频教程(SpringBoot版) ...

  2. asp.net Core 使用redis(StackExchange.Redis)

    原文:asp.net Core 使用redis(StackExchange.Redis) 一.添加配置(appsettings.json) "Redis": { "Def ...

  3. UniApp文件上传(SpringBoot+Minio)

    UniApp文件上传(SpringBoot+Minio) 一.Uni文件上传 (1).文件上传的问题 UniApp文件上传文档 uni.uploadFile({ url: 'https://www.e ...

  4. Spring session共享(使用redis)

    SpringBoot+Redis实现HttpSession共享 前提:需要使用redis做session存储 一.效果演练(这里使用SpringBoot工程,Spring同理) 1.一个工程使用两个端 ...

  5. Redis——学习之路一(初识redis)

    在接下来的一段时间里面我要将自己学习的redis整理一遍,下面是我整理的一些资料: Redis是一款依据BSD开源协议发行的高性能Key-Value存储系统(cache and store),所以re ...

  6. 带着萌新看springboot源码09(springboot+JdbcTemplate)

    emmm.....常规开局,继续说一下废话,前面简单的说了一下spring的ioc容器创建原理(花了不少时间去看了别人的博客+查了不少资料+自己的理解),相信大家对ioc容器有了一个初步的认识了. s ...

  7. 缓存知识整理(包含Redis)

    一.缓存知识 1.buffer和cache的区别 Buffer 缓冲 写操作 写缓冲    Cache 缓存 读操作 读缓存 磁盘-->内存-->CPU 2.PHP的缓存方案 官方文档:h ...

  8. 在.net中使用redis(StackExchange.Redis)

    本文介绍如何在.net中使用redis 安装 代码使用 StackExchange.Redis基础使用 StackExchange.Redis中的事务 安装(windows平台) 安装Chocolat ...

  9. summernote 上传图片到图片服务器的解决方案(springboot 成功)

    遇到的可以连接成功但是拒绝登录的问题 前提说一下,我自己在自己的服务器上配置了nginx的反向代理,所以请求的时候才会直接写的是我的ip地址,要配置nginx的话,可以看我的nginx的笔记 当代码感 ...

  10. SpringAOP使用及源码分析(SpringBoot下)

    一.SpringAOP应用 先搭建一个SpringBoot项目 <?xml version="1.0" encoding="UTF-8"?> < ...

随机推荐

  1. Markdown数学公式如何打出回归符号

    来源:https://blog.csdn.net/garfielder007/article/details/51646604 函数.符号及特殊字符 语法 效果 语法 效果 语法 效果 \bar{x} ...

  2. Web_0005:阿里云服务器OSS权限的配置开通

    创建用户 1,创建子用户 2,点击新建用户 3,设置账号类型,可以同时选 设置权限 1,设置对阿里云模块的控制权限,如 oss  ecs 等的访问控制权限 2,点击所需的权限 3,获取账号的Acess ...

  3. django orm介绍以及字段和参数

    Object Relational Mapping (ORM) orm介绍 orm概念 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数 ...

  4. 移动端display:flex

    移动端display:flex布局时候,子元素有背景颜色时候,背景颜色不能铺满,有缝隙, // less .t-flex { background: blue; display: flex; > ...

  5. CF1205E Expected Value Again

    题意 题意翻译 对于一个字符串\(s\),我们定义其美丽值\(f(s)\)为满足下列两个条件的正整数\(i\)的个数: \(1\leq i<|s|\) \(s\)长度为\(i\)的前缀与后缀相等 ...

  6. 浅析Thread的join() 方法

    Thread中的 join() 方法在实际开发过程中可能用的不是很多,但是在面试中作为考察基本功知识的扎实与否,经常会被用到.因此,对于 Thread 的 join() 方法进行了一定的研究. 常见的 ...

  7. AI机器人最高等级

    AI机器人最高等级 题目描述 在小朱朱的游戏世界里,有n个AI机器人. 他们相互之间可以进行PK,胜方存活且升一级,负方直接淘汰. 高等级AI必定战胜低等级AI,同等级AI的PK结果必定一胜一负,且规 ...

  8. HTML与W3C

    HTML:超文本标记语言 超文本包括:文字.图片.音频.视频.动画等 流程:写好HTML代码后通过浏览器(自动编译HTML代码)展现出效果 HTML优点: 世界知名浏览器厂商对HTML5的支持 微软 ...

  9. 在source insight project中删除文件夹或者文件的通用方法

    1.删除文件夹或者文件在硬盘上的数据 2.project->synchronize files...看到如下图,然后勾选remove missing files from project

  10. P5168 xtq玩魔塔 [克鲁斯卡尔重构树+带修莫队]

    P5168 xtq玩魔塔 又是码农题- 利用克鲁斯卡尔重构树的性质 我们就可以得出 \(dep\) 值小的,肯定比 \(dep\) 大的值要优. 于是第二问就可以直接 LCA 求出来了- 至于第三问, ...