String of Redis core data structure

Keywords: Java Spring Back-end Distribution

From common String commands to actual application scenario requirements design and development, this chapter enables you who are unfamiliar with redis to quickly master and understand, and you who are familiar with redis to quickly consolidate relevant knowledge

1, Characteristic description

(1) String is the most basic type of Redis. A key corresponds to a value;

(2) The String type is binary safe. This means that the redis String can contain any data. For example, jpg images or serialized objects;

(3) String type is the most basic data type of Redis. One key can store 512MB at most;

Binary security means that if the information security of binary data is guaranteed during data transmission, that is, it will not be tampered with or decoded. If it is attacked, it can be detected in time;

Binary security features:
    Encoding and decoding occur at the client, with high execution efficiency;
    There is no need for frequent encoding and decoding and no random code;
Copy code

2, Common commands

(1) SET

Command format:   SET   key value

Function: save string key value

demo Description:

(2) GET

Command format:   get   key

Function: get a string key value

demo Description:

(3) MSET

Command format:   MSET   key value [key value ]

Function: batch storage of string key values

demo Description:

(4) MGET

Command format:   mget key value [key value ]

Function: get string key values in batch

demo Description:

(5) SETNX

Command format:   setnx key value

Function: store a nonexistent string key value

demo Description: save a key as test444. The first time it succeeds, and the second time it already exists, it returns failure

(6) DEL

Command format:   setnx key value

Function: store a nonexistent string key value

demo Description:

(7) Exhibit

Command format:   setnx key value

Function: store a nonexistent string key value

demo Description:

(8) INCR

Command format:   incr key

Function: add one to the stored value in the key. If it does not exist for the first time, a key with a value of 0 will be created

demo Description:

(9) DECR

Command format:   decr key

Function: reduce the stored value in the key by one. If it does not exist for the first time, a key with a value of 0 will be created

demo Description:

(10) INCRBY

Command format:   incrby key increment

Function: add increment to the stored value in the key. If it does not exist for the first time, a key with a value of 0 will be created

demo Description:

(11) DECRBY

Command format:   incrby key increment

Function: subtract increment from the stored value in the key. If it does not exist for the first time, a key with a value of 0 will be created

demo Description:

3, Application scenario

Summarize the common production application scenarios, which are mainly divided into the following categories

(1) General data cache

Note: the following configuration data stored in mysql can be loaded into redis

1. Demand

saas service, each merchant can dynamically fill in their own payment configuration in the background, and need to cache it after each query

2. Design

  • When obtaining the configuration, first obtain the cache. If there is no data in the cache, query mysql. If yes, the configuration data will be returned directly
  • Query mysql to get the configuration data, cache the data in redis, and then return to the configuration
  • The cache key is designed as paysetting:payment: {service provider id}

3. Develop

//The main logic is written below. There is no exception handling logic, which needs to be supplemented by the little partner

public PaymentDto getPaymentSetting() throws Exception{
    ObjectMapper objectMapper = new ObjectMapper();

    //Query cache
    String key = "paysetting:payment:1";
    //Query cache
    PaymentDto paymentDto = objectMapper.readValue((String) redisTemplate.opsForValue().get(key), PaymentDto.class);
    if(ObjectUtils.isEmpty(paymentDto)){
        //query data base
        PaymentDto data = getData();
        //cache
        redisTemplate.opsForValue().set(key,objectMapper.writeValueAsString(data),3000,TimeUnit.SECONDS);
        return data;
    }
    //Return data
    return paymentDto;
}

//It is assumed that information is obtained from the database
private PaymentDto getData(){
    PaymentDto paymentDto = new PaymentDto();
    paymentDto.setAppId("98765365830261325");
    paymentDto.setAppSecret("fodkcjeuhaytwgvbdmi873tg4doo");
    return paymentDto;
}

(2) Object instance cache

Note: common object instances required by business can also be cached. Just like the spring framework startup, the singleton non lazy loaded object will be instantiated and cached into the JVM in advance

(3) Counter

Note: some business scenarios with high real-time requirements and frequent writes squeeze the performance of mysql and other databases. At this time, redis can be used to alleviate it. For example, the number of article likes and comments, or interface current limiting M

1. Demand

Some open interfaces need to limit the number of customer visits per day according to different package traffic

2. Design

  • Get the package configuration and get the maximum number of times customers can access the interface every day
  • Get the number of times that customers have accessed the interface today from the cache. Compare it with the maximum number. If it is equal to, it will return the prompt "today has reached the access limit". Otherwise, the number of records of the interface is increased by one
  • The cache key is designed as {interface id}: {year month day}: {service provider id}

3. Develop

//The main logic is written below. There is no exception handling logic, which needs to be supplemented by the little partner

public void limitInterface() throws Exception{
    //Get the package configuration and get the maximum number of times customers can access the interface every day
    Integer limitNum = getLimitNum();
    //key value
    String key = "findData:2021-11-26:100";
    
    //The query cache key is designed as {interface id}: {year month day}: {service provider id}
    String  count = (String) redisTemplate.opsForValue().get(key);

    Integer countNum = Integer.valueOf(count);
    
    if(countNum < limitNum){
        //Interface recording times plus one
        redisTemplate.opsForValue().increment(key);
        
        //Continue to execute business logic
    }else{
        System.out.println("Access limit reached today");
    }
}

public Integer getLimitNum(){
    //Fetching from the cache, the cache is not fetched from the database (after fetching from the database, it should be updated to the cache)

    return 100;
}

(4) Distributed lock

Note: using the setnx command of redis, only one client can successfully set a key value, so as to realize distributed lock.

(5) session sharing

Note: if multiple machines want to realize session sharing, they need to find a public place to store data, or to realize data synchronization. Obviously, redis can be a public place to store data.

(6) Distributed ID generation.

Note: in order to ensure the uniqueness of IDS, redis can uniformly generate a batch of IDS and then take them out for use

Posted by chrisdee on Sun, 28 Nov 2021 09:25:55 -0800