2019-07-31 简单分布式锁 springboot 2.0.2 +redis 解决没有setIfAbsent(Object key, Object value, long timeout,...

蛋疼问题,想使用

setIfAbsent(Object key, Object value, long timeout, TimeUnit unit)

方法解决多点和并发问题,但是由于redis版本问题不存在,只好曲线救国

  • springboot 2.0.2
  • springboot-redis 2.0.7
  • jedis 2.9.0

解决思路

1.没有就给他造一个,首先超看redis支持不支持,在查看存在该方法的源码;发现最终实现方法是在RedisStringCommands.class里面
使用的版本redis 方法中存在该方法,重新实现即可


@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    RedisSerializer keySerializer() {
        return this.redisTemplate.getKeySerializer();
    }

    RedisSerializer valueSerializer() {
        return this.redisTemplate.getValueSerializer();
    }
    byte[] rawKey(Object key) {
        Assert.notNull(key, "non null key required");
        return this.keySerializer() == null && key instanceof byte[] ? (byte[])((byte[])key) : this.keySerializer().serialize(key);
    }

    byte[] rawValue(Object value) {
        return this.valueSerializer() == null && value instanceof byte[] ? (byte[])((byte[])value) : this.valueSerializer().serialize(value);
    }

    /**
     *
     * @param key
     * @param value
     * @param timeout
     * @param unit
     * @return
     */
    public Boolean setIfAbsent(Object key, Object value, long timeout, TimeUnit unit) {
        byte[] rawKey = this.rawKey(key);
        byte[] rawValue = this.rawValue(value);
        Expiration expiration = Expiration.from(timeout, unit);
        return (Boolean)this.redisTemplate.execute((connection) -> {
            return connection.set(rawKey, rawValue, expiration, RedisStringCommands.SetOption.ifAbsent());
        }, true);
    }

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • NOSQL类型简介键值对:会使用到一个哈希表,表中有一个特定的键和一个指针指向特定的数据,如redis,volde...
    MicoCube阅读 4,058评论 2 27
  • 1 介绍 这篇博文讲介绍如何一步步构建一个基于Redis的分布式锁。会从最原始的版本开始,然后根据问题进行调整,最...
    Java黎先生阅读 508评论 0 2
  • 1 Redis介绍1.1 什么是NoSql为了解决高并发、高可扩展、高可用、大数据存储问题而产生的数据库解决方...
    克鲁德李阅读 5,354评论 0 36
  • 大雪不见雪, 地上铺满月。 点点灯光里, 吾娃要上学。
    俺在红尘阅读 619评论 11 20
  • 昨天2018.2.2阅读书目 一颗神奇树,我才不怕看牙医 瓢虫的日记 蝉的日记 爸爸烤的苹果派 过年啦
    惠鳞阅读 130评论 0 0