递增指令: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;
}
适用场景:
高并发生成订单号,秒杀类的业务逻辑等。。