Redisson分布式锁

  • Post author:
  • Post category:其他


引入依赖
<dependency>
   <groupId>org.redisson</groupId>
   <artifactId>redisson</artifactId>
   <version>3.7.5</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;
 
import java.io.IOException;
 
@Configuration
public class RedissonConfig {
 
    @Value("${spring.redis.host}")
    private String host;
 
    @Value("${spring.redis.port}")
    private String port;
 
    @Value("${spring.redis.password}")
    private String password;
 
    /**
     * RedissonClient,单机模式
     * @return
     * @throws IOException
     */
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() throws IOException {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password);
//        config.useSingleServer().setAddress("redis://" + host + ":" + port);
        return Redisson.create(config);
    }
}
使用
    @Autowired
    RedissonClient redissonClient;

    int n = 500;

    @ApiOperation("redisson测试")
    @GetMapping("/redisson/test")
    public ApiResponse testRedis() throws Exception {
        String LOCK_KEY = "hey";

        //定义锁
        RLock lock = redissonClient.getLock(LOCK_KEY);
        //lock.lock();
        try {

            //尝试加锁,最大等待时间300毫秒,上锁30毫秒自动解锁
            if (lock.tryLock(300, 30, TimeUnit.MILLISECONDS)) {
                Thread.sleep(5000);
                logger.info("线程:" + Thread.currentThread().getName() + "获得了锁");
                logger.info("剩余数量:{}", --n);
            }
        } catch (Exception e) {
            logger.error("程序执行异常:{}", e);
        } finally {
            logger.info("线程:" + Thread.currentThread().getName() + "准备释放锁");
            //释放锁
            lock.unlock();
        }
        return ApiResponse.success(n);
    }
结果:即使超时也不会释放锁,不会有A线程锁过期,B线程抢到锁同时扣库存的情况



版权声明:本文为m0_58709145原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。