JBoot中实现Redis的incrByFloat

JBoot的redis操作实例JBootRedisImpl类并没有封装Redis的incrByFloat方法,这带来了一定的不方便。但可以通过继承这个类,然后通过获取Jedis实例,调用Jedis原生方法来实现。需要注意的是Jedis调用完成后需要手动释放连接,否则会导致Redis连接池连接耗尽。

public class RedisHelper extends JBootRedisImpl{
    /**
     * 计数器,递增
     * @param key
     * @param step
     * @return
     */
    public static double incrByFloat(String key, double step){
        JbootJedisImpl jbootJedisImpl = null;
        Jedis jedis = null;
        try {
            jbootJedisImpl = (JbootJedisImpl) Jboot.me().getRedis();
            jedis = jbootJedisImpl.getJedis();
            return jedis.incrByFloat(key, step);
        } finally {
            if(jbootJedisImpl != null) {
                jbootJedisImpl.returnResource(jedis);
            }
        }
    }

    /**
     * 计数器,递减
     * @param key
     * @param step
     * @return
     */
    public static double decrByFloat(String key, double step){
        JbootJedisImpl jbootJedisImpl = null;
        Jedis jedis = null;
        try {
            jbootJedisImpl = (JbootJedisImpl) Jboot.me().getRedis();
            jedis = jbootJedisImpl.getJedis();
            return jedis.incrByFloat(key, step * -1);
        } finally {
            if(jbootJedisImpl != null) {
                jbootJedisImpl.returnResource(jedis);
            }
        }
    }
}

相关推荐