springboot11(springboot-redis)
一、Redis集群简介
1、RedisCluster概念
Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的需求,当一个服务宕机可以快速的切换到另外一个服务。redis cluster主要是针对海量数据+高并发+高可用的场景。
2、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)的更多相关文章
- Java商城秒杀系统的设计与实战视频教程(SpringBoot版)_汇总贴
51CTO学院 Java商城秒杀系统的设计与实战视频教程(SpringBoot版) H:\BaiDu\微服务0830\2019最新 Java商城秒杀系统的设计与实战视频教程(SpringBoot版) ...
- asp.net Core 使用redis(StackExchange.Redis)
原文:asp.net Core 使用redis(StackExchange.Redis) 一.添加配置(appsettings.json) "Redis": { "Def ...
- UniApp文件上传(SpringBoot+Minio)
UniApp文件上传(SpringBoot+Minio) 一.Uni文件上传 (1).文件上传的问题 UniApp文件上传文档 uni.uploadFile({ url: 'https://www.e ...
- Spring session共享(使用redis)
SpringBoot+Redis实现HttpSession共享 前提:需要使用redis做session存储 一.效果演练(这里使用SpringBoot工程,Spring同理) 1.一个工程使用两个端 ...
- Redis——学习之路一(初识redis)
在接下来的一段时间里面我要将自己学习的redis整理一遍,下面是我整理的一些资料: Redis是一款依据BSD开源协议发行的高性能Key-Value存储系统(cache and store),所以re ...
- 带着萌新看springboot源码09(springboot+JdbcTemplate)
emmm.....常规开局,继续说一下废话,前面简单的说了一下spring的ioc容器创建原理(花了不少时间去看了别人的博客+查了不少资料+自己的理解),相信大家对ioc容器有了一个初步的认识了. s ...
- 缓存知识整理(包含Redis)
一.缓存知识 1.buffer和cache的区别 Buffer 缓冲 写操作 写缓冲 Cache 缓存 读操作 读缓存 磁盘-->内存-->CPU 2.PHP的缓存方案 官方文档:h ...
- 在.net中使用redis(StackExchange.Redis)
本文介绍如何在.net中使用redis 安装 代码使用 StackExchange.Redis基础使用 StackExchange.Redis中的事务 安装(windows平台) 安装Chocolat ...
- summernote 上传图片到图片服务器的解决方案(springboot 成功)
遇到的可以连接成功但是拒绝登录的问题 前提说一下,我自己在自己的服务器上配置了nginx的反向代理,所以请求的时候才会直接写的是我的ip地址,要配置nginx的话,可以看我的nginx的笔记 当代码感 ...
- SpringAOP使用及源码分析(SpringBoot下)
一.SpringAOP应用 先搭建一个SpringBoot项目 <?xml version="1.0" encoding="UTF-8"?> < ...
随机推荐
- ABP前端-关于不同按钮调用同一事件传入的参数变为相同的数据
现象: 在一个含有的Tab标签的页面,两个标签页的新增按钮调用同一个新增事件并传入不同的参数,但实际在调用的的时候传入的参数都变成了最后一个按钮传入的值,即,不论点击哪个Tab按钮的新增事件,最终传入 ...
- Mac常用命令行
Mac环境下启动tomcat 1.进入文件夹----------cd apache-tomcat-9.0.10/ cd bin 2.启动tomcat---------sudo sh startup.s ...
- Python 变量&列表 初学者笔记
变量 消除空白后该变量需要存储一下(此操作常用于“储存用户输入并对其进行清理”) strip()消除两端空白 lstrip()消除前部空白 rstrip()消除末尾空白 upper()全部字母大写 ...
- Ansible Tower 3.5.1 平台部署和破解
原创 Ansible Tower 3.5.1 平台部署和破解 Ansible Tower (以前叫’AWX’)是能够帮助任何IT团队更容易使用Ansible的解决方案.该方案基于web. Tower允 ...
- nginx配置location与rewrite规则教程
location 教程 location 教程 示例: location = / { # 精确匹配 / ,主机名后面不能带任何字符串 [ configuration A ] }location / { ...
- shell awk学习3
需求: 某文件aa的内容如下: a/p1/p2b/pp1c/ppp1/ppp3d/p1/p2/p3e/p1/p2/p3/p4 期望输出结果: a /p1 /p2 b /pp1 c /ppp1 /ppp ...
- python全栈学习 day03
换行符: \n 制表符: \t 字符串截取:顾头不顾尾 s[首:尾:步长] 首--->尾走向 和 步长方向一致 s[0:4:2] s[4:0:-2] a = "qwertyui&quo ...
- Linux查看系统硬件信息命令
Linux查看系统硬件信息命令 查看磁盘类型(是否SSD) cat /sys/block/sda/queue/rotational code:0 SSD盘 code:1 SATA盘 查看物理CPU个数 ...
- python ide 使用
pycharm jupyter 官方文档 使用 部署到服务器 参考 配置域名(反向代理) *.conf文件 server { listen ; server_name ju.iii.top; inde ...
- 谈一谈php反序列化
1.序列化与反序列化 php中有两个函数serialize()和unserialize() 序列化serialize(): 当在php中创建了一个对象后,可以通过serialize()把这个对象转变成 ...