skip to Main Content

I need to create a counter in Redis, by default the method .incrBy() creates the counter with 0, but I need to start it with 123.
Do not want to handle it in my java code, how can I do it on Redis side? In transaction?

2

Answers


  1. Chosen as BEST ANSWER
        // (javadoc) If the field already exists, 0 is returned, otherwise if a new field is created 1 is returned
        if (redis.setnx(key, String.valueOf(initialValue)) != 1) {
            nextValue = redis.incrBy(key, increment);
        }
    

  2. I am not sure whether I get it right(please comment if not) but INCRBY takes second argument to set the counter to the given value for non existing keys.

    127.0.0.1:6379> GET key
    (nil)
    127.0.0.1:6379> INCRBY key 123
    (integer) 123
    127.0.0.1:6379> GET key
    "123"
    

    If the key exist, then increments the value of the existing.

    127.0.0.1:6379> GET key
    (nil)
    127.0.0.1:6379> SET key 10
    OK
    127.0.0.1:6379> INCRBY key 123
    (integer) 133
    127.0.0.1:6379> GET key
    "133"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search