Append appends the string

append name 2222
Copy the code

Strlen Obtains the length of the key string

strlen name
Copy the code

Three, self-increase, self-decrease

Article views, likes can do this.

incr age
decr age
Copy the code

Note that you need a number to do this, so you reset a key. The String type can hold both strings and numbers.

If step size is required:

incrby age 5
decrby age 8
Copy the code

String range

getrange name 1 3
Copy the code

getrange name 0 -1See all, similar to string interception in Python.

Replace the string

Specifies where to start replacing strings

setrange name 0 test
Copy the code

Set value and expiration time

setex

setex mykey 60 redis
Copy the code

Sets the value for the specified key and its expiration time. If the key already exists, the SETEX command replaces the old value.

The setnx setnx (SET if Not eXists) command sets a value for a key if the key does Not exist. This is often used in distributed locks.

setnx mykey redis333
Copy the code

If the key exists, the setting fails.

Seven, batch operation

1. The mset, mget

Mset, set more than one time.

mset k1 v1 k2 v2 k3 v3
Copy the code

Mget, get multiple at once.

mget k1 k2 k3
Copy the code

2. msetnx

Note that when multiple values are set, all fail if one of them fails.

msetnx k1 v1 k4 v4
Copy the code

Set a JSON object

In practical applications, where you might often want to save an object, redis can do some clever design with the colon:.

{name: pingguo, age:22} set it to user1.

mset user:1:name pingguo user:1:age 22

mget user:1:name user:1:age
Copy the code

Getset getSet getSet getSet

As it literally means, it gets the value first and then sets it. If no value exists, nil is returned. If so, get the old value and set the new value.

getset db mongodb
Copy the code