文章参考:
https://juejin.cn/post/7026291454532124680

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.2</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>cn.shutdown</groupId><artifactId>redission</artifactId><version>0.0.1-SNAPSHOT</version><name>redission</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><!-- 配置使用 redis 启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>3.13.6</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

application.yml

server:port: 9090address: 127.0.0.1#spring:
#  # Redis配置
#  redis:
#    timeout: 6000 # 连接超时时长(毫秒)
##    password:
#    database: 0
#    host: 127.0.0.1
#    port: 6379
#      #cluster:
#      #max-redirects: 3  # 获取失败 最大重定向次数
#      #nodes:
#    #- 192.168.104.101:6379
#    lettuce:
#      pool:
#        max-active: 1024 # 连接池最大连接数(默认为8,-1表示无限制 如果pool已经分配了超过max_active个jedis实例,则此时pool为耗尽)
#        max-wait: 10000 #最大等待连接时间,单位毫秒 默认为-1,表示永不超时,超时会抛出JedisConnectionException
#        max-idle: 10
#        min-idle: 5
spring:redis:database: 0host: 127.0.0.1jedis:pool:max-active: 8max-idle: 8max-wait: -1min-idle: 0password: 123456port: 6399timeout: 300

package cn.shutdown.redission;import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;import java.util.List;/*** Redis配置映射类** @author linmengmeng* @date 2021-03-11**/@Component
@ConfigurationProperties(prefix = "spring.redis")
public class RedisConfigProperties {private Integer timeout;private Integer database;private Integer port;private String host;private String password;private cluster cluster;public static class cluster {private List<String> nodes;public List<String> getNodes() {return nodes;}public void setNodes(List<String> nodes) {this.nodes = nodes;}}public Integer getTimeout() {return timeout;}public void setTimeout(Integer timeout) {this.timeout = timeout;}public Integer getDatabase() {return database;}public void setDatabase(Integer database) {this.database = database;}public Integer getPort() {return port;}public void setPort(Integer port) {this.port = port;}public String getHost() {return host;}public void setHost(String host) {this.host = host;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public RedisConfigProperties.cluster getCluster() {return cluster;}public void setCluster(RedisConfigProperties.cluster cluster) {this.cluster = cluster;}
}
package cn.shutdown.redission;import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** @author linmengmeng* @author 2021-08-30*/
@Configuration
public class RedissonConfig {@Autowiredprivate RedisConfigProperties redisConfigProperties;/*** redis://host:port*/private static final String REDIS_ADDRESS = "redis://%s:%s";//    /**//     * 集群模式-添加redisson的bean//     * @return//     *///    @Bean//    public Redisson redisson() {//        //redisson版本是3.5,集群的ip前面要加上“redis://”,不然会报错,3.2版本可不加//        List<String> clusterNodes = new ArrayList<>();//        for (int i = 0; i < redisConfigProperties.getCluster().getNodes().size(); i++) {//            clusterNodes.add("redis://" + redisConfigProperties.getCluster().getNodes().get(i));//        }//        Config config = new Config();//        ClusterServersConfig clusterServersConfig = config.useClusterServers()//                .addNodeAddress(clusterNodes.toArray(new String[clusterNodes.size()]));//        clusterServersConfig.setPassword(redisConfigProperties.getPassword());//设置密码//        return (Redisson) Redisson.create(config);//    }/*** Redisson单机模式* @return*/@Beanpublic Redisson RedissonConfig() {Config config = new Config();//        config.useSingleServer().setAddress("redis://localhost:6379").setDatabase(redisConfigProperties//        .getDatabase());config.useSingleServer().setAddress(String.format(REDIS_ADDRESS, redisConfigProperties.getHost(), redisConfigProperties.getPort())).setDatabase(redisConfigProperties.getDatabase()).setPassword(redisConfigProperties.getPassword());// 没有密码可以不设置return (Redisson) Redisson.create(config);}
}
package cn.shutdown.redission;import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;/*** @Auther linmengmeng* @Date 2021-09-01 15:37*/
@Slf4j
@RestController
@RequestMapping("/tourist")
public class TestRedissonLockController {private static String FORMAT_LOCKKEY = "testLockKey:%s";//分布式锁的key@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate Redisson redisson;@RequestMapping("/testLock11")public ApiResult<Boolean> testLock11() {String lockKey = String.format(FORMAT_LOCKKEY, 3);log.info("-------lockKey:{}", lockKey);RLock lock = redisson.getLock(lockKey);log.info("-------创建锁之后 isLocked-1:{}", lock.isLocked());//        try {//            Thread.sleep(10000);//        } catch (InterruptedException e) {//            e.printStackTrace();//        }Future<Boolean> res = lock.tryLockAsync(10, 30, TimeUnit.SECONDS);log.info("-------tryLockAsync 后 isLocked-2:{}", lock.isLocked());try {Thread.sleep(10000);} catch (InterruptedException e) {e.printStackTrace();}if (lock.isLocked()) {log.info("-------10秒 后----isLocked-3:{}", lock.isLocked());//throw new BusinessException("测试获取锁后发生异常");}if (lock.isHeldByCurrentThread()) {log.info("-------isHeldByCurrentThread:{}", lock.isHeldByCurrentThread());}boolean result = false;try {result = res.get();log.info("-------result:" + result);if (result) {Thread.sleep(10000);if (lock.isHeldByCurrentThread()) {log.info("-------isHeldByCurrentThread:{}", lock.isHeldByCurrentThread());}}} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();} finally {log.info("-------666666-------unlock-isLocked:{}", lock.isLocked());if (lock.isLocked()) {log.info("-------88888888-------解锁解锁:{}", lock.isLocked());lock.unlock();}}log.info("res.get:{}", result);return ApiResult.ok(lock.isLocked());}@RequestMapping("/testLock12")public ApiResult testLock12() {String lockKey = String.format(FORMAT_LOCKKEY, 3);log.info("====================lockKey:{}", lockKey);RLock lock = redisson.getLock(lockKey);log.info("====================isLocked-1:{}", lock.isLocked());Future<Boolean> res = lock.tryLockAsync(5, 2, TimeUnit.SECONDS);boolean locked = lock.isLocked();log.info("====================isLocked-2:{}", locked);if (locked) {if (lock.isHeldByCurrentThread()) {log.info("====================锁住了,是我的锁");} else {log.info("====================锁住了,不是我的锁");}}Boolean getLock = null;log.info("====================getLock-2:{}", getLock);return ApiResult.ok(locked);}}

redission分布式锁测试代码相关推荐

  1. spring定时任务(Scheduled)运行阻塞不执行/Redission分布式锁阻塞问题

    spring定时任务(Scheduled)运行阻塞不执行/Redission分布式锁阻塞问题 最近项目中发现一个bug,排查了很久,最后发现问题所在,在此记录一下. 问题描述: 项目运行一段时间后,c ...

  2. redis和redission分布式锁原理及区别

    redis和redission分布式锁原理及区别 我最近做租车项目,在处理分布式时用到分布式锁,我发现很多同事都在网上找分布式锁的资料,但是看的资料都不是很全,所以在这里我谈谈自己的分布式锁理解. 结 ...

  3. Redission 分布式锁原理

    Reddission 分布式锁原理 总结: 使用无参的tryLock()方法时,redisson会自动添加一个定时任务,定时刷新锁的失效时间,如果unlock时失败,则会出现该锁一直不释放的情况, 因 ...

  4. redisTemplate分布式锁演变、redission分布式锁实现!

    以下文章来源方志朋的博客,回复"666"获面试宝典 来源:blog.csdn.net/zhangkaixuan456 /article/details/110679617 分布式锁 ...

  5. redis分布式锁java代码_基于redis实现分布式锁

    " 在上一篇文章中介绍了动态配置定时任务,其中的原理跟spring 定时任务注解@Scheduled一样的,都是通过线程池和定义执行时间来控制.来思考一个问题,如果我们的定时任务在分布式微服 ...

  6. springboot 集成redission分布式锁

    Springboot整合Redisson 锁 一.依赖 <dependency><groupId>org.redisson</groupId><artifac ...

  7. 解决Redis分布式锁业务代码超时致使锁失效问题

    一.redis分布式锁的基本实现 redis加锁命令:redis SETNX resource_name my_random_value PX 30000 这个命令的做用是在只有这个key不存在的时候 ...

  8. redission分布式锁种类

    基于Redis的Redisson分布式可重入锁实现了java.util.concurrent.locks.Lock接口 Redisson 锁的种类有以下几种:可重入锁,公平锁,联锁,红锁,读写锁,接下 ...

  9. 分布式tensorflow测试代码

    数据集:minist  (我走的是本地读取) 数据集链接:https://pan.baidu.com/s/1o2faz60YLaba3q7hn_JWqg       提取码:yv3y 代码和数据集放在 ...

  10. 分布式锁--Redis小试牛刀

    参考文章: Redis分布式锁的正确实现方式 分布式锁看这篇就够了 在这两篇文章的指引下亲测 Redis分布式锁 引言 分布式系统一定会存在CAP权衡问题,所以才会出现分布式锁 什么是CAP理论? 为 ...

最新文章

  1. Linux内核网络栈1.2.13-socket.c函数概述
  2. 树链剖分 + 后缀数组 - E. Misha and LCP on Tree
  3. JavaFx 实用小工具超 60+ 大集合
  4. [Eclipse]GEF入门系列(七、XYLayout和展开/折叠功能)
  5. 【直播回放】60分钟了解各类图像和视频生成GAN结构
  6. php json -gt;访问,【转】Php+ajax+jsonp解决ajax跨域问题
  7. Java线程面试题 Top 53
  8. 搭建MVC及WebAPI项目框架时碰到的问题集合
  9. 【PostgreSQL-9.6.3】修改监听的IP和端口
  10. poj 3268 bzoj 1631: [Usaco2007 Feb]Cow Party(最短路)
  11. GitHub超详细图文攻略 - Git客户端下载安装 GitHub提交修改源码工作流程 Git分支 标签 过滤 Git版本工作流
  12. 计算机里的硬盘分区,Disk Genius对电脑硬盘分区的详细步骤
  13. kdj买卖指标公式源码_精品 玩转KDJ【精准买卖提示、源码、副图、说明】
  14. ORacle查询时显示同义词转换不再有效
  15. matlab拷贝不进u盘,Mac无法拷贝文件到U盘怎么办
  16. SSIS - Excel Destination无法接受大于255个字符长度的字符字段(转载)
  17. java实现模拟鼠标键盘操作
  18. php7的浮点数,php7.1浮点数运算问题
  19. [Linux]进程概念以及进程状态
  20. 盛京剑客系列22:一个成功的职业操盘手每天应做的三件事

热门文章

  1. Linux的i2c通讯协议
  2. POS-商户手续费-从生活剖析,通俗易懂
  3. 软件工程第1次作业—词频统计
  4. Codevs 1684 垃圾陷阱
  5. 多个table 相同col 的 设置相同width
  6. 【转载】C#字符串测试---------字符串截取,字符串分割
  7. python重定向作用_Python重定向不起作用
  8. 游戏筑基之两个变量交换值与三个变量交换值的比较(C语言)
  9. BGP增强特性(华为设备)
  10. 数据库与MySQL基本知识