Redis basic commands and Java API operations

Keywords: Database Redis

1, Redis basic commands

1.1. Operation of key

Keys *: view all keys in the current library     (matching: keys *1)
exists key: determines whether a key exists
type key: check the type of your key
del key: deletes the specified key data
unlink key: select non blocking deletion according to value (only delete keys from the metadata of the keyspace, and the real deletion will be performed in subsequent asynchronous operations.)
expire key 10:10 seconds: sets the expiration time for a given key
ttl key: check how many seconds have expired, - 1 means never expired, - 2 means expired

select: command to switch databases
dbsize: view the number of key s in the current database
flushdb: empty the current library
Flush: kill all libraries

//Set a value for (key)name> set name lucy 
OK> set age 10
//View all key s> keys *
1) "age"
2) "name"
//View the type of key> type age
string> type name
//Determine whether the key exists> exists age
(integer) 1> exists username
(integer) 0
//Deletes the specified key> del age
(integer) 1> keys *
1) "name"
//Set the expiration time for the specified key> expire name 10
(integer) 1
//View the expiration time of the specified key> ttl name
(integer) 4> ttl name
(integer) -2> ttl name
(integer) -2> set sex 0
//View the number of key s in the current database> dbsize
(integer) 1
//Switch the database with subscript 1, (the subscript of the database starts from 0)> select 1
OK[1]> set name cat
//Switch databases with subscript 0[1]> select 0
OK> set age 10
//Clear all database data> flushall
//The following command verifies that the emptying is successful> dbsize
(integer) 0> select 1
OK[1]> dbsize
(integer) 0[1]> select 0

1.2. String type common commands

Set < key > < value >: add a key value pair

get  < Key >: query the corresponding key value

Append < key > < value >: append the given < value > to the end of the original value

Strlen < key >: get the length of the value

Setnx < key > < value >: only when the key does not exist   Set the value of the key

Incr < key >: increase the digital value stored in the key by 1. You can only operate on the digital value. If it is empty, the new increment is 1

Decr < key >: subtract 1 from the digital value stored in the key. Only the digital value can be operated. If it is empty, the new increment is - 1

Incrby / decrby < key > < step size >: increase or decrease the digital value stored in the key. Custom step size.

Getrange < key > < start position > < end position >: obtain the range of values, similar to substring in java (pre package, post package)

Setrange < key > < start position > < value >: overwrite the string value stored in < key > with < value >, starting from < start position > (* * index starts from 0).

Setex < key > < expiration time > < value >: set the expiration time in seconds while setting the key value.

GetSet < key > < value >: replace the old with the new. Set the new value and obtain the old value at the same time

//Add key value pair> set k1 v1
//Get the value of the corresponding key> get k1
//Add abc after the value of the current key> append k1 abc
(integer) 5
//Get the value of the key to check whether abc has joined successfully> get k1
//View the length of the current key> strlen k1
(integer) 5
//When the current key does not exist, add the key value pair. Here, the key k1 exists, so the addition fails> setnx k1 a
(integer) 0
//The key k2 does not exist here, so it is added successfully> setnx k2 1
(integer) 1
//Increment the value of the specified key by 1> incr k2
(integer) 2> get k2
//Subtract 1 from the value of the specified key> decr k2
(integer) 1> get k2
//Increase the number of steps of 10 for key k2> incrby k2 10
(integer) 11> get k2
//Get the value in the subscript corresponding to key k1 (before and after the package)> getrange k1 0 1
//Overwrite na with the value of key k1 starting with subscript 0> setrange k1 0 na
(integer) 5> get k1
//Add the key value pair k3 and set the expiration time in seconds> setex k3 2 v3
//After 2 seconds, the view key is found to have expired> get k3
//Set the new value 100 to key k2 and return to the old value 11> getset k2 100
"11"> get k2

  1.3 list type common commands

Lpush / rpush < key > < value1 > < Value2 > < value3 >...: insert one or more values from the left / right.

Lpop / rpop < key > [count]: pop up a value from the left / right (the value will be deleted), and count indicates the number of pop-up values set (optional). (when all the values corresponding to the key are popped up, the key will also be deleted)

Rpoplpush < key1 > < key2 >: pop up a value from the right of the < key1 > list and insert it to the left of the < key2 > list.

Lrange < key > < start > < stop >: get the elements according to the index subscript (from left to right) (0 to - 1 means get all)

Lindex < key > < index >: get the element (from left to right) according to the index subscript (the value will not be deleted)

Len < key >: get the length of the list  

Linsert < key > before < value > < newvalue >: insert < newvalue > from the front of < value > (the before here can also be changed to after, indicating to insert from the back)

Lrem < key > < n > < value >: delete n values from the left (from left to right)

Lset < key > < index > < value >: replace the value with index in the list key

//Add list value from left> lpush k1 v1 v2 v3
(integer) 3
//Get the value of list k1 from left to right> lrange k1 0 -1
1) "v3"
2) "v2"
3) "v1"
//Pop up a value of k1 from the left (the value will be deleted)> lpop k1 
"v3"> lpush k2 redis java mysql
(integer) 3
//Pop up a value of k1 from the right and insert it into k2 from the left> rpoplpush k1 k2
//Verify that the previous operation pop-up succeeded> lrange k1 0 -1
1) "v2"
//Verify that the previous operation was inserted successfully> lrange k2 0 -1
1) "v1"
2) "mysql"
3) "java"
4) "redis"
//Gets k2 a value with a subscript of 0> lindex k2 0
"v1"> lrange k2 0 -1
1) "v1"
2) "mysql"
3) "java"
4) "redis"
//Get the length of k2> llen k2
(integer) 4
//Insert abc before the value v2 of k1> linsert k1 before v2 abc
(integer) 2
//Verify that the previous operation was successful> lrange k1 0 -1
1) "abc"
2) "v2"
//Delete an element with mysql value from the left of k2> lrem k2 1 mysql
(integer) 1
//Check whether the operation is successful> lrange k2 0 -1
1) "v1"
2) "java"
3) "redis"
//Replace the value of list k2 subscript 0 with mysql> lset k2 0 mysql
//Check whether the operation is successful> lrange k2 0 -1
1) "mysql"
2) "java"
3) "redis"

1.4 set type common commands  

Sadd < key > < value1 > < Value2 >....: add one or more member elements to the set key, and the existing member elements will be ignored

Smembers < key >: fetch all values of the set.

Sismember < key > < value >: judge whether the set < key > contains the < value > value, with 1 and no 0

Scar < key >: returns the number of elements in the collection

SREM < key > < value1 > < Value2 >...: deletes an element in the set.

Spop < key >: pop up a value randomly from the set. (the value will be deleted)

Srandmember < key > < n >: randomly take n values from the set. Is not removed from the collection.

Smove < source > < destination > value: moves a value in a set from one set to another

Sinter < key1 > < key2 >: returns the intersection elements of two sets.

Sun ion < key1 > < key2 >: returns the union elements of two sets.

Sdiff < key1 > < key2 >: returns the difference elements of two sets (those in key1, excluding those in key2)

//Add a key value pair of type set> sadd k1 v1 v2 v3
(integer) 3
//Fetch all values of set k1> smembers k1
1) "v1"
2) "v2"
3) "v3"
//Determine whether the value v4 exists in the set k1> sismember k1 v4
(integer) 0
//View the length of the set k1> scard k1
(integer) 3
//Delete element v3 in set k1> srem k1 v3
(integer) 1
//Randomly pop up a value from the set k1.> spop k1
//The verification pop-up value will be deleted> smembers k1
1) "v1"
//Take a value from the random set k1> srandmember k1 1
1) "v1"
//Verify that the extracted value will not be deleted> smembers k1
1) "v1"> sadd k2 a b c
(integer) 3
//Remove element a from set k2 and add it to k1> smove k2 k1 a
(integer) 1
//Verify that the addition was successful> smembers k1
1) "a"
2) "v1"
//Verify that the removal was successful> smembers k2
1) "c"
2) "b"
//Returns the intersection element of two collections> sinter k1 k2
(empty array)
//Returns the union element of two collections> sunion k1 k2
1) "c"
2) "a"
3) "v1"
4) "b"
//Returns the difference element of two sets (key1 does not contain the element in key2)> sdiff k1 k2
1) "a"
2) "v1"

1.5. Common hash commands  

Hset < key > < field > < value >: to the  < Field > key assignment < value >

Hget < key1 > < field >: fetch value from < key1 > set < field >  

Hmset < key1 > < field1 > < value1 > < field2 > < Value2 >...: set hash values in batch

Hexists < key1 > < field >: check whether the given field exists in the hash table key.  

Hkeys < key >: lists all field s of the hash set

Hvals < key >: lists all value s of the hash set

Hincrby < key > < field > < increment >: add an increment of 1 to the value of the field in the hash table key   - one

Hsetnx < key > < field > < value >: set the value of the field in the hash table key to value, which is valid if and only if the field does not exist

//Assign a value to the name attribute in k1> hset k1 name lisi
(integer) 1
//Get the value of the name attribute in k1> hget k1 name
//Batch add attributes and values in k1> hmset k1 age 10 sex 0
//Judge whether the attribute name exists in k1> hexists k1 name
(integer) 1
//View all attributes in k1> hkeys k1
1) "name"
2) "age"
3) "sex"
//View the values of all attributes in k1> hvals k1
1) "lisi"
2) "10"
3) "0"
//Add increment 2 to the value of attribute age in k1> hincrby k1 age 2
(integer) 12
//View results> hget k1 age
//Set the value of attribute name in k1 to lusy. Because the attribute name exists, it is valid when setting fails> hsetnx k1 name lusy
(integer) 0
//Set the value of the attribute phone in k1 to 123. Because the attribute phone does not exist, the setting is successful> hsetnx k1 phone 123
(integer) 1

1.6. zset common commands

zadd  < Key > < Score1 > < value1 > < score2 > < Value2 >...: add one or more member elements and score values to the ordered set key.

zrange <key> <start> <stop>   [with scores]: returns the elements in the ordered set key with subscripts between < start > < stop >, with with with scores, so that scores and values can be returned to the result set.

Zrange key min max byscore [WithCores] [limit offset count]: returns all score values in the ordered set key between min and max      (including members equal to min or max). (without byscore,min and Max represent subscripts), the members of the ordered set are arranged in the order of increasing score value (from small to large).  

zrevrange key max min   [WithCores] [limit offset count]: same as above, change from large to small columns.  

Zincrby < key > < increment > < value >: adds an increment to the score of an element

zrem  < Key > < value >: deletes the element with the specified value under the set  

Zcount < key > < min > < Max >: count the number of elements in the score interval of the set  

Zrank < key > < value >: returns the ranking of the value in the collection, starting from 0. (from small to large)

//Add one or more elements and their score values to the ordered set k1.> zadd k1 500 v1 100 v2 300 v3
(integer) 3
//Returns the elements in the ordered set k1 with subscripts between 0 and 1 and with fractional bands> zrange k1 0 -1 withscores
1) "v2"
2) "100"
3) "v3"
4) "300"
5) "v1"
6) "500"
//Returns the elements and scores with scores between 200 and 600 in k1 and arranges them from small to large> zrange k1 200 600 byscore withscores
1) "v3"
2) "300"
3) "v1"
4) "500"
//Returns the elements and fractions with subscripts between 0 and 2 in k1 and arranges them from large to small> zrevrange k1 0 2 withscores
1) "v1"
2) "500"
3) "v3"
4) "300"
5) "v2"
6) "100"
//Add 100 to the fraction where the element in k1 is v1> zincrby k1 100 v1
//Delete element v3 in k1> zrem k1 v3
(integer) 1
//Count elements with scores from 100 to 500 in k1> zcount k1 100 500
(integer) 1
//Returns the ranking of element v2 in k1 (from small to large)> zrank k1 v2
(integer) 0
//Returns the ranking of element v1 in k1 (from small to large)> zrank k1 v1
(integer) 1

2, Common API operations

2.1 preparation

Comment out bind in redis.conf, change yes in protected mode yes to no, and then close the firewall of Linux, otherwise other devices will not be able to connect to redis in Linux

1. Open redis.conf with vi editor

2. Command mode: use the: / bind command to find bind, use i to enter the editing mode and comment it out

3. Use the same method to find protected mode yes and change yes to no

4. Use esc to exit the editing mode, and use the: wq command to save and exit

5. Execute the systemctl stop firewalld command to close the firewall

6. Restart redis

The current status indicates that the firewall is turned off

2.2 test

The Jedis object contains all Redis command operations, so you can use the Jedis object to operate Redis

2.2.1 import dependency


2.2.2 test API operation

public class Demo1 {

    public static void main(String[] args) {
        //Create Jedis object
        // the ip address of Linux. redis is started on Linux
        //6379: redis port number
        Jedis jedis = new Jedis("",6379);
        //Test whether the connection is successful
        String pong =;
        System.out.println("Successfully connected:" + pong);


         * Operation Key

        Set<String> keys = jedis.keys("*");
        for (String key : keys) {

        //Check whether the current key exists
        //View the expiration time of the key
        //Get the value of key


         * Operation String
        //Stores multiple key value pairs of string types
        //Get the value of multiple key s


         * Action List
        List<String> mylist = jedis.lrange("mylist", 0, -1);
        for (String s : mylist) {


         * Operation set
        Set<String> orders = jedis.smembers("orders");
        for (String order : orders) {


         * Operation hash
        Map<String, String> map = new HashMap<String, String>();
        //Add map
        jedis.hmset("hash2", map);
        List<String> result = jedis.hmget("hash2", "phone", "age", "email");
        for (String s : result) {


         * Operation zset

        Set<String> zset01 = jedis.zrange("zset01", 0, -1);
        for (String s : zset01) {


2.2.3 results

Successfully connected: PONG
[v1, v2, v3]

Posted by racing_fire on Mon, 04 Oct 2021 20:08:37 -0700