学无先后,达者为师

网站首页 编程语言 正文

使用Redission实现分布式锁

作者:自由_free 更新时间: 2022-05-11 编程语言

1.使用Redission实现分布式锁

  • 添加pom依赖
<dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.8.2</version>
        </dependency>
  • 在项目中将需要的参数配置到配置文件中

在这里插入图片描述

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName RedissonConfig
 * @Description TODO
 * @Author LZJ
 * @Date 2021/6/17 11:43
 * @Version 1.0
 */
@Configuration
public class RedissonConfig {

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

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

    @Bean
    public RedissonClient getClient() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://"+host+":"+port);
        RedissonClient redisson = Redisson.create(config);
        return redisson;
    }

}
  • 在需要加锁的函数中添加代码(registerUser(message)为主函数),最后在finally中释放锁
                      try {
                                    boolean tryLock = lock.tryLock(2, 8, TimeUnit.SECONDS);
                                    if (tryLock) {
                                        registerUser(message);
                                    }

                                } catch (Exception e) {
                                    log.error("redission  error e:{} ", e);
                                    e.printStackTrace();
                                } finally {
                                    lock.unlock();
                                }
                            }

原文链接:https://blog.csdn.net/weixin_49194846/article/details/118087301

栏目分类
最近更新