码迷,mamicode.com
首页 > 其他好文 > 详细

Redis适用于高并发的递增、递减功能

时间:2016-09-07 14:36:57      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

递增指令: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;
    }

适用场景:

  高并发生成订单号,秒杀类的业务逻辑等。。

Redis适用于高并发的递增、递减功能

标签:

原文地址:http://www.cnblogs.com/jager/p/5849269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!