SoFunction
Updated on 2025-03-03

Five basic types of Redis, business scenarios and usage methods

What is Redis?

Redis is a non-relational database. Redis is an open source high-performance key-value database, mainly used for data storage and caching.

It supports a variety of data structures such as strings, hashes, lists, collections and ordered collections.

Features of Redis

  1. Rich data types‌: Redis not only supports key-value pairs of string type, but also supports a variety of data structures such as lists, hashes, sets and ordered sets, which enables Redis to handle more complex data operations‌23.
  2. high performance‌: Since data is stored in memory, Redis can provide extremely high read and write speeds, suitable for scenarios that require high-speed responses‌12.
  3. Persistence function‌: Redis supports periodic writing of data in memory to disk to ensure data security. It also supports writing modification operations to additional record files to realize master-slave synchronization‌14.
  4. Scalability‌: Redis provides rich API and scripting functions, supports batch execution of commands through Lua scripts, and also supports horizontal expansion, similar to library and table division

rely

<!--  SpringBoot Boot Redis  -->
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>jedis</artifactId>
</dependency>
<!-- Spring Boot Starter Test -->
<dependency>
     <groupId></groupId>
     <artifactId>spring-boot-starter-test</artifactId>
     <scope>test</scope>
  </dependency>
<!-- JUnit 5 -->
<dependency>
      <groupId></groupId>
      <artifactId>junit-jupiter-api</artifactId>
      <version>5.8.2</version>
      <scope>test</scope>
</dependency>
<dependency>
      <groupId></groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <version>5.8.2</version>
      <scope>test</scope>
</dependency>

Configuration

spring:
  redis:
    host: yourip
    port: 6379

Redis configuration class (used for format conversion and handling garbled code)

package ;

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .Jackson2JsonRedisSerializer;
import ;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate&lt;String, Object&gt; template = new RedisTemplate&lt;&gt;();
        (factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new
                Jackson2JsonRedisSerializer();
        ObjectMapper om = new ObjectMapper();
        (, );
        (.NON_FINAL);
        (om);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // The key adopts the serialization method of String        (stringRedisSerializer);
        // The hash key also uses String serialization method        (stringRedisSerializer);
        // value serialization method uses jackson        (jackson2JsonRedisSerializer);
        // The value serialization method of hash uses jackson        (jackson2JsonRedisSerializer);
        ();

        return template;
    }
}

String (String)

Features

  • The most basic data type can contain any type of data, such as integers, floating point numbers, or strings.
  • The maximum storage capacity is 512MB.

Business scenarios

  • Cache: Store temporary data, such as user session information or page cache.
  • Counter: It can be used to realize self-increase functions such as access counters and likes.
  • Configuration storage: Stores the configuration parameters of the application.

Code Use Cases

import ;
import ;
import ;
import ;

import static ;

@SpringBootTest
public class StringExampleTest {

    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    @Test
    public void testString() {
        // Set string value        ().set("myStringKey", "Hello Redis!");

        // Get and verify the string value        String value = (String) ().get("myStringKey");
        assertEquals("Hello Redis!", value);  // Verify that the value is correct
        // Update string value        ().set("myStringKey", "Updated Value");
        assertEquals("Updated Value", ().get("myStringKey"));  // Verify the updated value
        // Increase the counter value        ().increment("myCounter", 1);
        assertEquals(1, ().get("myCounter"));  // Verify the counter value
        // Set string with expiration time        ().set("tempKey", "I will expire soon", 10);
        // Verify that the expiration time is less than 10 seconds (the actual expiration time may be slightly less than 10 seconds)        assertEquals(true, ("tempKey") &lt; 10L);
    }
}

Notice:

  • If the generics and configuration classes are different during injection, it may not be able to use the configuration class's related configuration, and the original configuration of redisTemplate will be used, and the data stored in redis will be some garbled code.
  • It is necessary to ensure that the injected generics are the same as the configuration class, so that the data stored in redis is correct.

List (list)

Features

  • Is a linked list structure that can contain multiple string values ​​(elements).
  • You can insert (push) and delete (pop) operations on both ends of the list, and support trimming (trim) the list to retain elements in the specified range.

Business scenarios

  • Message Queue: Implement producer/consumer model through lists.
  • Timeline: A timeline that stores user activity logs or social media.
  • Task Scheduling: A queue that stores pending tasks.

Code Use Cases

import ;
import ;
import ;
import ;

import ;

import static ;

@SpringBootTest
public class ListExampleTest {

    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    @Test
    public void testList() {
        // Add elements to the list        ().leftPush("myListKey", "item1");
        ().leftPush("myListKey", "item2");

        // Get and verify all elements in the list        List&lt;Object&gt; list = ().range("myListKey", 0, -1);
        assertEquals(true, ("item2"));  // Verification list contains item2        assertEquals(true, ("item1"));  // Verification list contains item1
        // Pop up element from list        Object poppedItem = ().rightPop("myListKey");
        assertEquals("item1", poppedItem);  // Verify that the pop-up element is item1
        // Get the list length        Long size = ().size("myListKey");
        assertEquals(1L, size);  // Verify list length is 1
        // Insert new element at the beginning of the list        ().insert("myListKey", 0, "item0");
        List&lt;Object&gt; updatedList = ().range("myListKey", 0, -1);
        assertEquals(true, ("item0"));  // Verification list contains item0        assertEquals(true, ("item2"));  // The verification list still contains item2    }
}

Notice:

  • If the generics and configuration classes are different during injection, it may not be able to use the configuration class's related configuration, and the original configuration of redisTemplate will be used, and the data stored in redis will be some garbled code.
  • It is necessary to ensure that the injected generics are the same as the configuration class, so that the data stored in redis is correct.

Set (set)

Features

  • It is an unordered collection of strings, and the elements in the collection are unique, that is, repetition is not allowed.
  • It supports intersection, union, difference and other operations between sets, and can be used to process common friends, tags and other data of multiple users.

Business scenarios

  • Tag system: A tag that stores user's interest tags or articles.
  • Friendship relationship: Store user's friend list and quickly find common friends.
  • Deduplication: used for deduplication operations, such as counting the number of independent visitors.

Code Use Cases

import ;
import ;
import ;
import ;

import ;

import static ;
import static ;

@SpringBootTest
public class SetExampleTest {

    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    @Test
    public void testSet() {
        // Add elements to the collection        ().add("mySetKey", "member1", "member2", "member3");

        // Get and verify all members in the collection        Set&lt;Object&gt; members = ().members("mySetKey");
        assertEquals(true, ("member1"));  // Verify that the set contains member1        assertEquals(true, ("member2"));  // Verify that the set contains member2        assertEquals(true, ("member3"));  // Verify that the set contains member3
        // Delete a member from the collection        ().remove("mySetKey", "member2");
        assertFalse(().members("mySetKey").contains("member2"));  // Verify that member2 has been deleted
        // Check if a member is in the collection        Boolean isMember = ().isMember("mySetKey", "member1");
        assertEquals(true, isMember);  // Verify that member1 is still in the collection    }
}

Notice:

  • If the generics and configuration classes are different during injection, it may not be able to use the configuration class's related configuration, and the original configuration of redisTemplate will be used, and the data stored in redis will be some garbled code.
  • It is necessary to ensure that the injected generics are the same as the configuration class, so that the data stored in redis is correct.

Hash (hash table)

Features

  • is a key-value pair collection that is suitable for storing objects.
  • Each Hash can store up to 2^32 - 1 key-value pairs (over 4 billion).
  • Suitable for storing and reading entire objects, such as user information, product information, etc.

Business scenarios

  • User Information: Stores basic information about users, such as username, email address, and other attributes.
  • Product Attributes: Store detailed information of the product, such as price, description, inventory, etc.
  • Status information: Used to store state information, such as the current state of a session or task.

Code Use Cases

import ;
import ;
import ;
import ;

import ;
import ;

import static ;
import static ;

@SpringBootTest
public class HashExampleTest {

    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    @Test
    public void testHash() {
        // Create a HashMap and store it in Redis        Map&lt;String, Object&gt; myHash = new HashMap&lt;&gt;();
        ("field1", "value1");
        ("field2", "value2");
        ().putAll("myHashKey", myHash);

        // Get and verify the hash field value        String fieldValue = (String) ().get("myHashKey", "field1");
        assertEquals("value1", fieldValue);  // Verify field values
        // Update the hash field        ().put("myHashKey", "field1", "newValue");
        assertEquals("newValue", ().get("myHashKey", "field1"));  // Verify the updated value
        // Delete the hash field        ().delete("myHashKey", "field2");
        assertFalse(().hasKey("myHashKey", "field2"));  // Verify that the field has been deleted
        // Get all fields and their values        Map&lt;Object, Object&gt; entries = ().entries("myHashKey");
        assertEquals(true, ("field1"));  // Verify that the field exists        assertEquals("newValue", ("field1"));  // Verify field values    }
}

Notice:

  • If the generics and configuration classes are different during injection, it may not be able to use the configuration class's related configuration, and the original configuration of redisTemplate will be used, and the data stored in redis will be some garbled code.
  • It is necessary to ensure that the injected generics are the same as the configuration class, so that the data stored in redis is correct.

Sorted Set (ordered set)

Features

  • Similar to a set, each member is unique, but each member will associate a floating point value called score.
  • Members are sorted by scores, and members can be obtained by score ranges or rankings by scores.
  • Suitable for scenarios where you need to sort and range query based on scores, such as ranking lists, timelines, etc.

Business scenarios

  • Ranking list: Store user points, rankings, etc., and you can quickly query the top N users.
  • Timestamp sort: Store event logs according to the sort of timestamps.
  • Priority queue: Implement task scheduling and handle tasks according to priority.

Code Use Cases

import ;
import ;
import ;
import ;

import ;

import static ;
import static ;

@SpringBootTest
public class ZSetExampleTest {

    @Autowired
    private RedisTemplate&lt;String, Object&gt; redisTemplate;

    @Test
    public void testZSet() {
        // Add elements to an ordered collection        ().add("myZSetKey", "member1", 1);
        ().add("myZSetKey", "member2", 2);

        // Get and verify all members in the ordered collection        Set&lt;Object&gt; zSetMembers = ().range("myZSetKey", 0, -1);
        assertEquals(true, ("member1"));  // Verify that member1 exists        assertEquals(true, ("member2"));  // Verify that member2 exists
        // Update the element's fraction        ().incrementScore("myZSetKey", "member1", 3);
        Double score = ().score("myZSetKey", "member1");
        assertEquals(4.0, score);  // Verify that the score of member1 is updated to 4.0
        // Get members within the specified score range        Set&lt;Object&gt; rangeByScore = ().rangeByScore("myZSetKey", 1, 2);
        assertEquals(true, ("member2"));  // Verify that member2 is within the score range
        // Delete a member from an ordered collection        ().remove("myZSetKey", "member2");
        assertFalse(().range("myZSetKey", 0, -1).contains("member2"));  // Verify that member2 has been deleted    }
}

Notice:

  • If the generics and configuration classes are different during injection, it may not be able to use the configuration class's related configuration, and the original configuration of redisTemplate will be used, and the data stored in redis will be some garbled code.
  • It is necessary to ensure that the injected generics are the same as the configuration class, so that the data stored in redis is correct.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.