使用spring redis包操作redis进行incr操作

 
    //自增方法 
    public Long incr(String key, long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        //初始设置过期时间
        if ((null == increment || increment.longValue() == 0) && liveTime > 0) {
            //liveTime为秒数
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);
        }
        return increment;
    }
    //生成批次号
    private String getOrder() {
        String order = "";
        //incr初始值为0,一般需求初始值为1,所以进行判断0的操作
        Long incr = this.incr("key" , 5);
        if (incr == 0) {
            //设置自增key  key 5秒后过期, 过期时间的设定只在新增key时有效
            incr = this.incr("key" , 5);
        }
        DecimalFormat df = new DecimalFormat("00000");
        order = df.format(incr);
        return order;
    }
 

 

返回有序集合的值:

 @RequestMapping("/redisGet")
    public String testGet() {

        Set> rangeWithScores =                 
        redisTemplate.opsForZSet().rangeByScoreWithScores("key",0,10);
        Iterator> iterator = rangeWithScores.iterator();
        while(iterator.hasNext()){
            ZSetOperations.TypedTuple next = iterator.next();
            System.out.println("value:"+next.getValue()+" score:"+next.getScore());
            score =next.getScore();
        }
        return "keysNumber="+this.redisTemplate.opsForZSet().size("key")+"score:"+score;
    }

 

 

你可能感兴趣的:(redis,数据库)