实现redis分布式锁

springboot工程。redis哨兵

1.配置redis模板

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
public class RedisConfig {


    @Bean
    public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory redisConnectionFactory){

        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
 
        return redisTemplate;
    }

}

2.实现redis分布式锁

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
public class RedisDistributedLock {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private Logger logger = LoggerFactory.getLogger(RedisDistributedLock.class);

    //redis分布式锁的默认超时时间
    private static final Long DEFAULT_LOCK_TIMEOUT = 60*1000L;

    //redis分布式锁的的value
    private static final Integer LOCK_KEY_VALUE = 1;

    /**
     * 获取锁
     * @param lockKey   lockKey
     * @return          true获取到锁,false未获取到锁
     */
    public boolean lock(String lockKey){
        return lock(lockKey,DEFAULT_LOCK_TIMEOUT);
    }

    /**
     * 获取锁
     * @param lockKey   lockKey
     * @param timeout   锁超时时间,单位ms
     * @return
     */
    public boolean lock(String lockKey,long timeout){
        logger.info("==============》开始执行加锁操作");
        if(StringUtils.isEmpty(lockKey)){
            logger.error("传递字符串为空,不能进行加锁");
            return false;
        }
        Boolean lockResult = redisTemplate.execute((RedisCallback<Boolean>) connection -> {
            JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer();
            byte[] value = jdkSerializer.serialize(LOCK_KEY_VALUE);
            return connection.setNX(lockKey.getBytes(), value);
        });
        if(lockResult){
            logger.info("获取锁成功,设置锁超时时间");
            redisTemplate.expire(lockKey, timeout, TimeUnit.MILLISECONDS);
        }
        return lockResult;
    }


    /**
     * 进行解锁操作
     * @param lockKey    lockKey
     */
    public void unLock(String lockKey){
        logger.info("==============》开始执行解锁操作");
        if(StringUtils.isEmpty(lockKey)){
            logger.error("传递字符串为空,不能进行解锁");
            return ;
        }
        Integer redisLockKeyValue = (Integer)redisTemplate.opsForValue().get(lockKey);
        if(redisLockKeyValue != null && redisLockKeyValue > 0){
            redisTemplate.delete(lockKey);
        }
    }


}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值