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

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

  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
127.0.0.1:6379> lpush k1 v1 v2 v3
(integer) 3
//Get the value of list k1 from left to right
127.0.0.1:6379> lrange k1 0 -1
1) "v3"
2) "v2"
3) "v1"
//Pop up a value of k1 from the left (the value will be deleted)
127.0.0.1:6379> lpop k1 
"v3"
127.0.0.1:6379> lpush k2 redis java mysql
(integer) 3
//Pop up a value of k1 from the right and insert it into k2 from the left
127.0.0.1:6379> rpoplpush k1 k2
"v1"
//Verify that the previous operation pop-up succeeded
127.0.0.1:6379> lrange k1 0 -1
1) "v2"
//Verify that the previous operation was inserted successfully
127.0.0.1:6379> lrange k2 0 -1
1) "v1"
2) "mysql"
3) "java"
4) "redis"
//Gets k2 a value with a subscript of 0
127.0.0.1:6379> lindex k2 0
"v1"
127.0.0.1:6379> lrange k2 0 -1
1) "v1"
2) "mysql"
3) "java"
4) "redis"
//Get the length of k2
127.0.0.1:6379> llen k2
(integer) 4
//Insert abc before the value v2 of k1
127.0.0.1:6379> linsert k1 before v2 abc
(integer) 2
//Verify that the previous operation was successful
127.0.0.1:6379> lrange k1 0 -1
1) "abc"
2) "v2"
//Delete an element with mysql value from the left of k2
127.0.0.1:6379> lrem k2 1 mysql
(integer) 1
//Check whether the operation is successful
127.0.0.1:6379> lrange k2 0 -1
1) "v1"
2) "java"
3) "redis"
//Replace the value of list k2 subscript 0 with mysql
127.0.0.1:6379> lset k2 0 mysql
OK
//Check whether the operation is successful
127.0.0.1:6379> 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
127.0.0.1:6379> sadd k1 v1 v2 v3
(integer) 3
//Fetch all values of set k1
127.0.0.1:6379> smembers k1
1) "v1"
2) "v2"
3) "v3"
//Determine whether the value v4 exists in the set k1
127.0.0.1:6379> sismember k1 v4
(integer) 0
//View the length of the set k1
127.0.0.1:6379> scard k1
(integer) 3
//Delete element v3 in set k1
127.0.0.1:6379> srem k1 v3
(integer) 1
//Randomly pop up a value from the set k1.
127.0.0.1:6379> spop k1
"v2"
//The verification pop-up value will be deleted
127.0.0.1:6379> smembers k1
1) "v1"
//Take a value from the random set k1
127.0.0.1:6379> srandmember k1 1
1) "v1"
//Verify that the extracted value will not be deleted
127.0.0.1:6379> smembers k1
1) "v1"
127.0.0.1:6379> sadd k2 a b c
(integer) 3
//Remove element a from set k2 and add it to k1
127.0.0.1:6379> smove k2 k1 a
(integer) 1
//Verify that the addition was successful
127.0.0.1:6379> smembers k1
1) "a"
2) "v1"
//Verify that the removal was successful
127.0.0.1:6379> smembers k2
1) "c"
2) "b"
//Returns the intersection element of two collections
127.0.0.1:6379> sinter k1 k2
(empty array)
//Returns the union element of two collections
127.0.0.1:6379> 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)
127.0.0.1:6379> 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
127.0.0.1:6379> hset k1 name lisi
(integer) 1
//Get the value of the name attribute in k1
127.0.0.1:6379> hget k1 name
"lisi"
//Batch add attributes and values in k1
127.0.0.1:6379> hmset k1 age 10 sex 0
OK
//Judge whether the attribute name exists in k1
127.0.0.1:6379> hexists k1 name
(integer) 1
//View all attributes in k1
127.0.0.1:6379> hkeys k1
1) "name"
2) "age"
3) "sex"
//View the values of all attributes in k1
127.0.0.1:6379> hvals k1
1) "lisi"
2) "10"
3) "0"
//Add increment 2 to the value of attribute age in k1
127.0.0.1:6379> hincrby k1 age 2
(integer) 12
//View results
127.0.0.1:6379> hget k1 age
"12"
//Set the value of attribute name in k1 to lusy. Because the attribute name exists, it is valid when setting fails
127.0.0.1:6379> 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
127.0.0.1:6379> 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.
127.0.0.1:6379> 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
127.0.0.1:6379> 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
127.0.0.1:6379> 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
127.0.0.1:6379> 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
127.0.0.1:6379> zincrby k1 100 v1
"600"
//Delete element v3 in k1
127.0.0.1:6379> zrem k1 v3
(integer) 1
//Count elements with scores from 100 to 500 in k1
127.0.0.1:6379> zcount k1 100 500
(integer) 1
//Returns the ranking of element v2 in k1 (from small to large)
127.0.0.1:6379> zrank k1 v2
(integer) 0
//Returns the ranking of element v1 in k1 (from small to large)
127.0.0.1:6379> zrank k1 v1
(integer) 1

2, Common API operations

2.1 preparation

Comment out bind 127.0.0.1 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 127.0.0.1, 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

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.3.0</version>
</dependency>

2.2.2 test API operation

public class Demo1 {

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

        System.out.println("==============key==============");

        /**
         * Operation Key
         */
        jedis.set("k1","v1");
        jedis.set("k2","v2");
        jedis.set("k3","v3");

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

        //Check whether the current key exists
        System.out.println(jedis.exists("k1"));
        //View the expiration time of the key
        System.out.println(jedis.ttl("k1"));
        //Get the value of key
        System.out.println(jedis.get("k1"));

        System.out.println("==============String==============");

        /**
         * Operation String
         */
        //Stores multiple key value pairs of string types
        jedis.mset("str1","v1","str2","v2","str3","v3");
        //Get the value of multiple key s
        System.out.println(jedis.mget("str1","str2","str3"));

        System.out.println("==============list==============");

        /**
         * Action List
         */
        jedis.lpush("mylist","l1","l2","l3");
        List<String> mylist = jedis.lrange("mylist", 0, -1);
        for (String s : mylist) {
            System.out.println(s);
        }

        System.out.println("==============set==============");

        /**
         * Operation set
         */
        jedis.sadd("orders","order01","order02","order03");
        Set<String> orders = jedis.smembers("orders");
        for (String order : orders) {
            System.out.println(order);
        }

        System.out.println("==============hash==============");

        /**
         * Operation hash
         */
        jedis.hset("hash1","username","lisi");
        System.out.println(jedis.hget("hash1","username"));
        Map<String, String> map = new HashMap<String, String>();
        map.put("phone","10000000000");
        map.put("age","20");
        map.put("email","abc@123.com");
        //Add map
        jedis.hmset("hash2", map);
        List<String> result = jedis.hmget("hash2", "phone", "age", "email");
        for (String s : result) {
            System.out.println(s);
        }

        System.out.println("==============zset==============");

        /**
         * Operation zset
         */
        jedis.zadd("zset01",100d,"z3");
        jedis.zadd("zset01",90d,"l4");
        jedis.zadd("zset01",80d,"w5");
        jedis.zadd("zset01",70d,"z6");

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

    }
}

2.2.3 results

Successfully connected: PONG
==============key==============
k3
k1
k2
true
-1
v1
==============String==============
[v1, v2, v3]
==============list==============
l3
l2
l1
==============set==============
order01
order03
order02
==============hash==============
lisi
10000000000
20
abc@123.com
==============zset==============
z6
w5
l4
z3

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