SpringBoot如何使用Redis做分布式锁

什么是Redis

Redis(Remote Dictionary Server)是一个开源的内存数据库,遵守 BSD 协议,它提供了一个高性能的键值(key-value)存储系统,常用于缓存、消息队列、会话存储等应用场景。

SpringBoot 如何接入
  1. 引入依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
  1. 配置yml
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 3
    password: pwd
  1. 进行测试

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    
    @Test
    public void setValueByKey() {
        // 设置缓存 参数为 key value 数字 日期类型
        redisTemplate.opsForValue().set("TEST:KEY","TEST",1L, TimeUnit.DAYS);
    }

    @Test
    public void getValueByKey() {
        // 根据key 获取value
        String value = redisTemplate.opsForValue().get("TEST:KEY");
    }
接入redisson做分别式锁
  1. 引入依赖
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.13.4</version>
        </dependency>
  1. 编写配置类
public class RedissonConfig {
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private String port;

    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public RedissonClient getRedissonClient() {
        Config config = new Config();
        String address = "redis://".concat(host).concat(":").concat(port);
        config.useSingleServer().setAddress(address);
        config.useSingleServer().setPassword(password);
        return Redisson.create(config);
    }

}
  1. 进行测试
    @Test
    public void lock() throws InterruptedException {
        RLock lock = redissonClient.getLock("lock");
        lock.tryLock(1,1,TimeUnit.MINUTES);
        // 业务代码
        lock.unlock();
    }

畅联AIoT开放云平台(www.24hlink.cn)由杭州美畅物联技术有限公司精心打造,不仅能够接入视频,也可以接入、管理各种IoT设备、工业现场设备,在AIoT开发领域能给合作伙伴带来难以置信的的降本增效价值。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值