Redis適用於高並發的遞增、遞減功能


遞增指令:incr(默認從0開始)

遞減指令:decr(默認從0開始,遞減會出現負數,這點跟memcache不一樣,mc到0)

如下:

附上shardedJedisPool和JedisCluster的兩種實現方式:

shardedJedisPool:

@Override
    public Long decr(String key) {
        ShardedJedis jedis = null;
        Long result = 0l;
        try {
            jedis =  shardedJedisPool.getResource();
            result = jedis.decr(key);
        } catch (Exception e) {
            log.error("redis decr error and key = " + key, e);
        }
        return result;
    }

    @Override
    public Long incr(String key) {
        ShardedJedis jedis = null;
        Long result = 0l;
        try {
            jedis =  shardedJedisPool.getResource();
            result = jedis.incr(key);
        } catch (Exception e) {
            log.error("redis incr error and key = " + key, e);
        }
        return result;
    }

JedisCluster:

@Override
    public Long decr(String key) {
        Long result = 0l;
        try {
            result = jedisCluster.decr(key);
        } catch (Exception e) {
            log.error("jedisCluster decr error and key = " + key, e);
        }
        return result;
    }

    @Override
    public Long incr(String key) {
        Long result = 0l;
        try {
            result = jedisCluster.incr(key);
        } catch (Exception e) {
            log.error("jedisCluster incr error and key = " + key, e);
        }
        return result;
    }

適用場景:

  高並發生成訂單號,秒殺類的業務邏輯等。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM