当前位置:网站首页>Systematic and detailed explanation of redis operation hash type data (with source code analysis and test results)

Systematic and detailed explanation of redis operation hash type data (with source code analysis and test results)

2022-07-06 19:30:00 Natural player

1 origin

Systematic explanation Redis Of Hash type CURD,
Help learners learn systematically and accurately Hash Data manipulation ,
Gradually develop the good habit of testing ,
In this paper, a long ,Hash There are many operations , Please be patient ,
You can concentrate on watching , You can also spend time learning .

important clause :

(1) All test codes are attached at the end of the paper ;
(2) This article will learn to use the following functions ( Method ):

Serial number operation method
1 newly added hset,hmset,hsetnx
2 Delete hdel
3 modify hset,hmset,hincr,hincrBy,hincrByFloat
4 Inquire about hget,hmget,hgetAll,hkeys,hvals,hexists

(3) rely on

<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.5.1</version>
</dependency>

(4) About several terms :Redis data type hash, When using , There are three concepts :key,field,value,
among ,key by hash Variable name ,field namely HashMap The key ,value namely HashMap The value in , later , If it is a special statement ,
Using keys means HashMap The key .

2 Hash Type operation

Redis Medium hash Type data , For standard Java Of HashMap, Store key value pairs , however Redis Medium hash The value of can only be of string type ,rehash On HashMap Also different .
Redis Of hash To improve performance , Using progressive rehash.

2.1 Connection pool

private static JedisPool getJedisPool() {
    
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // Jedis pool : maximum connection 
        jedisPoolConfig.setMaxTotal(1);
        // Jedis pool : Maximum number of free connections 
        jedisPoolConfig.setMaxIdle(10);
        // Jedis pool : Waiting time 
        jedisPoolConfig.setMaxWaitMillis(3000);
        // Jedis pool : Connect Redis Timeout time 
        int connectTimeout = 2000;
        String redisHost = "127.0.0.1";
        int redisPort = 6379;
        String redisPassword = "123456";
        int redisDb = 0;
        //  Create connection pool 
        return new JedisPool(jedisPoolConfig, redisHost, redisPort, connectTimeout, redisPassword, redisDb);
    }

2.2 insert data

Insert data yes 3 Ways of planting : Single insertion 、 Multiple inserts 、 Conditional insertion .

2.2.1 Single insertion :hset

Insert nonexistent data for the first time , After successful writing, return 1, If you modify the data for the second time , Successfully modified , return 0,
therefore , Can't use hset The returned data of determines whether the writing or modification is successful ,
Only one piece of data can be inserted at a time ,
The test code snippet is as follows :

    /** *  Single insert data  */
    @Test
    public void insertData() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Long res1 = jedis.hset("userScore", "xiaoyi", "19");
            Long res2 = jedis.hset("userScore", "xiaoer", "20");
            Long res3 = jedis.hset("userScore", "xiaosan", "20");
            logger.info(">>>>>>>>Redis Insert Hash data :{}, {}, {}", res1, res2, res3);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Insert Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure .
 Insert picture description here

The data format is shown in the figure below , When querying data , according to userScore Locate the Hash, Then take the value of the corresponding key .

 Insert picture description here
hset The source code is shown in the figure below , It can be seen from the notes ,hset It will create new data (Redis Can't exist ), The data will be updated again (Redis There is old data ).
Location :redis.clients.jedis.Jedis#hset(java.lang.String, java.lang.String, java.lang.String)
 Insert picture description here

2.2.2 Batch insert :hmset

above hset Only a single piece of data can be inserted ,
Is there a way to insert more than one at a time ?
yes , we have ,hmset You can insert multiple at one time , Direct will Map Insert Redis,
The test code snippet is as follows :

    /** *  Bulk insert data  */
    @Test
    public void insertDataBatch() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Map<String, String> userScore = new HashMap<>();
            userScore.put("xiaosi", "22");
            userScore.put("xiaowu", "20");
            String res1 = jedis.hmset("userScore", userScore);
            logger.info(">>>>>>>>Redis Insert Hash data :{}", res1);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Insert Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results show that , Successful insertion returns :OK.
 Insert picture description here

The new data is shown in the figure below :
 Insert picture description here

hmset The source code is shown in the figure below , It can be seen from the notes ,hash If there is no data in, create a new ,hmset There's data , Will replace the old value .
Location :redis.clients.jedis.Jedis#hmset
 Insert picture description here

2.2.3 Insert nonexistent data :hsetnx

If you just need to Hash Add new data to , Old data remains unchanged , What do I do ?
hsetnx That is to meet this demand ,
Only add nonexistent data ,
The test code snippet is as follows :

    /** *  Conditional insert data : * Redis The attribute insertion does not exist , Otherwise do not insert  */
    @Test
    public void insertDataIfNotExist() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            // ("xiaoyi", "19") Already exists , Will not insert , Old data will not be updated 
            Long res1 = jedis.hsetnx("userScore", "xiaoyi", "10");
            // ("xiaoliu", "10") non-existent , It will insert 
            Long res2 = jedis.hsetnx("userScore", "xiaoliu", "10");
            logger.info(">>>>>>>>Redis Insert Hash data :{}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Insert Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure , From the results ,0 Indicates existing data ,1 Indicates new data ,
stay hsetnx in ,0 Indicates that data already exists , No updates ;1 Express : The new data .
 Insert picture description here
The source code is shown in the figure below , We can know from the source code ,hsetnx Only change nonexistent data .
Location :redis.clients.jedis.Jedis#hsetnx
 Insert picture description here

2.3 Delete data :hdel

Delete data , about hash type , The version Redis The library provides a hdel Method ,
Support deleting one or more ,
The test code snippet is as follows :

    /** *  Delete data  */
    @Test
    public void deleteData() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Long res1 = jedis.hdel("userScore", "xiaoyi");
            Long res2 = jedis.hdel("userScore", "xiaoer", "xiaosan");
            logger.info(">>>>>>>>Redis Delete Hash data :{}, {}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Delete Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure ,hdel The returned data is the number of successfully deleted data ,
If you return 0, said , No data was deleted .
 Insert picture description here

hdel The source code is shown in the figure below , It can be seen from the notes , The time complexity is O(1).
Location :redis.clients.jedis.Jedis#hdel

 Insert picture description here

2.4 Modifying data

The modified data includes 3 Kind of : Directly modify the content 、 Change the pure numeric value according to the integer step 、 Change the pure numeric value according to the floating-point step .

2.4.1 Directly modifying :hset

hset It is a function for adding and modifying reuse ( Method ), When adding data above, we will explain , Not much here , Only test code segments and test results are given .

    /** *  Edit the data : Directly modifying  */
    @Test
    public void editData() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Long res1 = jedis.hset("userScore", "xiaoyi", "6");
            logger.info(">>>>>>>>Redis modify Hash data :{}", res1);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis modify Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure .
 Insert picture description here

2.4.2 Specify integer step size modification :incrBy

This function is very interesting , The value of data can be changed according to integer steps ,
In particular : A positive number increases , Negative numbers decrease .
The test code snippet is as follows :

    /** *  Update numeric type in specified integer steps , *  Positive numbers : increase  *  negative : Reduce  */
    @Test
    public void increaseByData() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Long res1 = jedis.hincrBy("userScore", "xiaoyi", 2);
            Long res2 = jedis.hincrBy("userScore", "xiaoyi", -5);
            logger.info(">>>>>>>>Redis modify Hash data :{}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis modify Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

hincrBy The source code is shown in the figure below , It can be seen from the notes , If the added key does not exist , Data will be created , It supports both increasing and decreasing functions .
Location :redis.clients.jedis.Jedis#hincrBy

 Insert picture description here

2.4.3 Specify floating point step size modification :incrByFloat

Change data according to floating-point step , seeing the name of a thing one thinks of its function , Use floating-point numbers as units of change .
In particular : A positive number increases , Negative numbers decrease .
The test code snippet is as follows :

    /** *  Update numeric type in specified floating-point step , *  Positive numbers : increase  *  negative : Reduce  */
    @Test
    public void increaseByFloatData() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Double res1 = jedis.hincrByFloat("userScore", "xiaoyi", 2.0);
            Double res2 = jedis.hincrByFloat("userScore", "xiaoyi", -2.0);
            logger.info(">>>>>>>>Redis modify Hash data :{}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis modify Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

hincrByFloat Source code is as follows , It can be seen from the notes , Processing floating point data , If there is no data, create new data .
Location :redis.clients.jedis.Jedis#hincrByFloat

 Insert picture description here

2.5 Query data

hash The data type is a key value pair , therefore , Data query is also multifarious ,
Such as , Query all the data ( key + value )、 Query all keys (keys)、 Query all values (values) etc. .

2.5.1 Query all the data :hgetAll

Query all the data , If the machine memory is enough or does not affect the business , You can query all data directly ,
Data structures put into code Map Do code caching in ,
The test code snippet is as follows :

    /** *  Query all the data  */
    @Test
    public void queryDataAll() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Map<String, String> res = jedis.hgetAll("userScore");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}", res);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure , Find all the results .
 Insert picture description here
hgetAll The source code is shown in the figure below , It can be seen from the notes , Query all hash data .
Location :redis.clients.jedis.Jedis#hgetAll
 Insert picture description here

2.5.2 Query a piece of data :hget

Query single data , Use hget, Specify the value of the key ,
The test code snippet is as follows :

    /** *  Query single data  */
    @Test
    public void queryDataOne() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            String res1 = jedis.hget("userScore", "xiaoyi");
            String res2 = jedis.hget("userScore", "xio");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure , Just to mention here , If the key of the query does not exist , Then return to null.
 Insert picture description here
hget Source code is as follows , It can be seen from the notes , For keys that do not exist, return null value .
Location :redis.clients.jedis.Jedis#hget
 Insert picture description here

2.5.3 Batch query :hmget

Sometimes we need to query data within a specified range ,
Too much data , Unable to query all data at once ,
therefore , You can use the batch query function :hmget,
The test code snippet is as follows :

    /** *  Bulk query data : Specify properties  */
    @Test
    public void queryDataBatch() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            List<String> res1 = jedis.hmget("userScore", "xiaoyi", "xiaoer");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}", res1);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure ,
 Insert picture description here
hmget The source code is shown in the figure below , It can be seen from the notes , The query process , Encountered non-existent data , return null.
Location :redis.clients.jedis.Jedis#hmget
 Insert picture description here

2.5.4 Query all key names :hkeys

For judged business scenarios , You can only iterate over whether a key exists ,
in the first place , Only check the key data volume and all data ( key + value ) comparison , There will be a lot less ;
both , The query speed will also be improved ;
therefore , With , Just check hash Key :hkeys,
The test code snippet is as follows :

    /** *  Query all properties (HashMap The key ) */
    @Test
    public void queryDataAllKeys() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Set<String> res = jedis.hkeys("userScore");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}", res);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure , Return to the list of keys .
 Insert picture description here
hkeys The source code is shown in the figure below , It can be seen from the notes , return hash All attribute names .
Location :redis.clients.jedis.Jedis#hkeys
 Insert picture description here

2.5.5 Query all values :hvals

There is a query key in front , that , If there is a scenario where you need to query only values , What do I do ?
Of course , There are ways to :hvals,
Provide the function of only querying values , It only needs to do business or relevant calculation according to the value ,
The test code snippet is as follows :

    /** *  Query all values  */
    @Test
    public void queryDataAllValues() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            List<String> res = jedis.hvals("userScore");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}", res);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure , From the results , The returned data is of list type .
 Insert picture description here
hvals The source code is shown in the figure below , It can be seen from the notes , return hash All worth .
Location :redis.clients.jedis.Jedis#hvals

 Insert picture description here

2.5.6 Number of query data :hlen

Sometimes , We need to judge whether to synchronize all the data to Redis,
perhaps , Need to check hash Data volume ,
This is where we need to use it hlen, Query a current hash The amount of data ,
The test code snippet is as follows :

    /** *  Inquire about Hash The number of data in  */
    @Test
    public void queryDataLength() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Long res = jedis.hlen("userScore");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}", res);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure , From the results , At present hash,userScore Store 4 Data .
 Insert picture description here
hlen The source code is shown in the figure below , If the inquiry hash No data or no hash Then return to 0.
Location :redis.clients.jedis.Jedis#hlen
 Insert picture description here

2.5.7 Query whether the data exists :hexists

This is a click function , Determine whether a specified key exists ,
There is no need to use temporary variables to store ,
Direct condition judgment , because ,hexists The direct return is Boolean ,
The test code snippet is as follows :

    /** *  Query whether a property exists  */
    @Test
    public void queryDataExistsOrNot() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Boolean res1 = jedis.hexists("userScore", "xiaoyi");
            Boolean res2 = jedis.hexists("userScore", "xiao");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

The test results are shown in the following figure , To be is to return true, Returns if it does not exist false.
 Insert picture description here
hexists The source code is shown in the figure below , It can be seen from the notes , Judge hash key ( attribute ) Whether there is .
Location :redis.clients.jedis.Jedis#hexists
 Insert picture description here

3 Summary

The core :
(1) Add data :
A single article is added : Directly add :hset,key If it doesn't exist, add ,key If it exists, the old value is overwritten ;
A single article is added : New condition :hsetnx,key If it doesn't exist, add ,key There is no operation ;
Batch add :hmset;
(2) Delete data : It can be deleted individually or in batches ;
(3) modify : Modify data usage hset perhaps hmset, Cover old values directly . If you need to increase or decrease data , You can use pure digital data , Specify the step size plus or minus , Support integer step size and floating point step size , Add and subtract through the positive and negative of the step ;
(4) Query data : Single query (hget), Return single data ; Multiple queries (hmget), Return list data , Query all the data 、 All keys ( attribute )、 All worth .

Serial number operation method
1 newly added hset,hmset,hsetnx
2 Delete hdel
3 modify hset,hmset,hincr,hincrBy,hincrByFloat
4 Inquire about hget,hmget,hgetAll,hkeys,hvals,hexists

The attachment

Complete test samples

package database_test.redis_test;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/** * Hash Data type operations . * * @author xindaqi * @since 2022-07-03 9:12 */
public class HashTest {
    

    private static final Logger logger = LoggerFactory.getLogger(HashTest.class);

    private static JedisPool getJedisPool() {
    
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // Jedis pool : maximum connection 
        jedisPoolConfig.setMaxTotal(1);
        // Jedis pool : Maximum number of free connections 
        jedisPoolConfig.setMaxIdle(10);
        // Jedis pool : Waiting time 
        jedisPoolConfig.setMaxWaitMillis(3000);
        // Jedis pool : Connect Redis Timeout time 
        int connectTimeout = 2000;
        String redisHost = "127.0.0.1";
        int redisPort = 6379;
        String redisPassword = "123456";
        int redisDb = 0;
        //  Create connection pool 
        return new JedisPool(jedisPoolConfig, redisHost, redisPort, connectTimeout, redisPassword, redisDb);
    }

    /** *  Single insert data  */
    @Test
    public void insertData() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Long res1 = jedis.hset("userScore", "xiaoyi", "66");
            Long res2 = jedis.hset("userScore", "xiaoer", "20");
            Long res3 = jedis.hset("userScore", "xiaosan", "20");
            logger.info(">>>>>>>>Redis Insert Hash data :{}, {}, {}", res1, res2, res3);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Insert Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Bulk insert data  */
    @Test
    public void insertDataBatch() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Map<String, String> userScore = new HashMap<>();
            userScore.put("xiaosi", "22");
            userScore.put("xiaowu", "20");
            String res1 = jedis.hmset("userScore", userScore);
            logger.info(">>>>>>>>Redis Insert Hash data :{}", res1);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Insert Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Conditional insert data : * Redis The attribute insertion does not exist , Otherwise do not insert  */
    @Test
    public void insertDataIfNotExist() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            // ("xiaoyi", "19") Already exists , Will not insert , Old data will not be updated 
            Long res1 = jedis.hsetnx("userScore", "xiaoyi", "10");
            // ("xiaoliu", "10") non-existent , It will insert 
            Long res2 = jedis.hsetnx("userScore", "xiaoliu", "10");
            logger.info(">>>>>>>>Redis Insert Hash data :{}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Insert Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Delete data  */
    @Test
    public void deleteData() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Long res1 = jedis.hdel("userScore", "xiaoyi");
            Long res2 = jedis.hdel("userScore", "xiaoer", "xiaosan");
            logger.info(">>>>>>>>Redis Delete Hash data :{}, {}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Delete Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Edit the data : Directly modifying  */
    @Test
    public void editData() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Long res1 = jedis.hset("userScore", "xiaoyi", "6");
            logger.info(">>>>>>>>Redis modify Hash data :{}", res1);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis modify Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Update numeric type in specified integer steps , *  Positive numbers : increase  *  negative : Reduce  */
    @Test
    public void increaseByData() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Long res1 = jedis.hincrBy("userScore", "xiaoyi", 2);
            Long res2 = jedis.hincrBy("userScore", "xiaoyi", -5);
            logger.info(">>>>>>>>Redis modify Hash data :{}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis modify Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }


    /** *  Update numeric type in specified floating-point step , *  Positive numbers : increase  *  negative : Reduce  */
    @Test
    public void increaseByFloatData() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Double res1 = jedis.hincrByFloat("userScore", "xiaoyi", 2.0);
            Double res2 = jedis.hincrByFloat("userScore", "xiaoyi", -2.0);
            logger.info(">>>>>>>>Redis modify Hash data :{}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis modify Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Query all the data  */
    @Test
    public void queryDataAll() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Map<String, String> res = jedis.hgetAll("userScore");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}", res);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Query single data  */
    @Test
    public void queryDataOne() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            String res1 = jedis.hget("userScore", "xiaoyi");
            String res2 = jedis.hget("userScore", "xio");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Bulk query data : Specify properties  */
    @Test
    public void queryDataBatch() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            List<String> res1 = jedis.hmget("userScore", "xiaoyi", "xiaoer");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}", res1);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }


    /** *  Query all properties (HashMap The key ) */
    @Test
    public void queryDataAllKeys() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Set<String> res = jedis.hkeys("userScore");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}", res);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Query all values  */
    @Test
    public void queryDataAllValues() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            List<String> res = jedis.hvals("userScore");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}", res);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Inquire about Hash The number of data in  */
    @Test
    public void queryDataLength() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Long res = jedis.hlen("userScore");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}", res);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }

    /** *  Query whether a property exists  */
    @Test
    public void queryDataExistsOrNot() {
    
        try (Jedis jedis = getJedisPool().getResource()) {
    
            Boolean res1 = jedis.hexists("userScore", "xiaoyi");
            Boolean res2 = jedis.hexists("userScore", "xiao");
            logger.info(">>>>>>>>Redis Inquire about Hash data :{}, {}", res1, res2);
        } catch (Exception ex) {
    
            logger.error(">>>>>>>>Redis Inquire about Hash Data exception :", ex);
            throw new RuntimeException(ex);
        }
    }
}
原网站

版权声明
本文为[Natural player]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061131318522.html

随机推荐