公众号:架构师与哈苏
关注公众号进入it交流群! 公众号:架构师与哈苏 不定时都会推送一些实用的干货。。。

RedisLockUtil.java
package com.meeno.inner.oa.common.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @description: redis锁工具类
 * @author: Wzq
 * @create: 2020-09-09 11:34
 */
@Component
@Slf4j
public class RedisLockUtil {

    private static RedisTemplate<String, Object> redisTemplate;

    private static StringRedisTemplate stringRedisTemplate;

    @Autowired
    private void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate){
        RedisLockUtil.stringRedisTemplate = stringRedisTemplate;
    }

    @Autowired
    private void setUserMessageService(RedisTemplate<String, Object> redisTemplate){
        RedisLockUtil.redisTemplate = redisTemplate;
    }

    /**
     * 加锁
     * @param key
     * @param value
     * @param timeout 过期时间
     */
    public static boolean lock(String key, String value, Integer timeout){
        Boolean b = stringRedisTemplate.opsForValue().setIfAbsent(key, value,timeout, TimeUnit.SECONDS);
        //Boolean b1 = redisTemplate.opsForValue().setIfAbsent(key, value,timeout, TimeUnit.SECONDS);
        if(b){
            return true;
        }else{
            log.info("lock err!");
        }
        return false;
    }

    /**
     * 释放锁
     * @param key
     */
    public static void releaseLock(String key){
        redisTemplate.delete(key);
        log.info("releaseLock success!");
    }



}

posted on 2020-09-16 12:15  公众号/架构师与哈苏  阅读(3171)  评论(0编辑  收藏  举报