REDIS实现使用setNX实现锁功能,可实现分布式锁功能,包含锁失效时间

package com.suyun.vehicle.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.time.Clock;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class VehicleSetNXUtil<K, V> {
    private static final Logger logger = LoggerFactory.getLogger(VehicleSetNXUtil.class);
    @Autowired
    private RedisTemplate<K, V> redisTemplate;
    /**
     * 默认失效时间10*60秒
     */
    private static final Long TIME_OUT = 600L;

    public Boolean setNX(K key) {
        Boolean flag = redisTemplate.boundHashOps(key).putIfAbsent("redisLock", "测试时间" + Clock.systemDefaultZone().millis());
        redisTemplate.boundHashOps(key).expire(TIME_OUT, TimeUnit.SECONDS);
        return setNX(key, TIME_OUT, TimeUnit.SECONDS);
    }

    /**
     * redis设置锁失效时间,默认单位为秒
     *
     * @param key
     * @param seconds
     * @return
     */
    public Boolean setNX(K key, final Long seconds) {
        Boolean flag = redisTemplate.boundHashOps(key).putIfAbsent("redisLock", "测试时间" + Clock.systemDefaultZone().millis());
        redisTemplate.boundHashOps(key).expire(seconds, TimeUnit.SECONDS);
        return setNX(key, seconds, TimeUnit.SECONDS);
    }

    /**
     * MICROSECONDS    微秒   一百万分之一秒(就是毫秒/1000)
     * MILLISECONDS    毫秒   千分之一秒
     * NANOSECONDS   毫微秒  十亿分之一秒(就是微秒/1000)
     * SECONDS          秒
     * MINUTES     分钟
     * HOURS      小时
     * DAYS      天
     *
     * @param key
     * @param seconds
     * @param timeUnit
     * @return
     */
    public Boolean setNX(K key, final Long seconds, TimeUnit timeUnit) {
        Boolean flag = redisTemplate.boundHashOps(key).putIfAbsent("redisLock", "测试时间" + Clock.systemDefaultZone().millis());
        redisTemplate.boundHashOps(key).expire(seconds, timeUnit);
        return flag;
    }
}

猜你喜欢

转载自blog.csdn.net/xionglangs/article/details/81334032