SoFunction
Updated on 2025-04-11

How to use redis in SpringBoot

one,

 <dependencies>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId></groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 </dependencies>

two,

# Redis Server Address=192.168.11.84
# Redis Server Connection Port=6379
# Redis server connection password (default is empty)=
# Redis database index (default is 0) 15 total=0
## Connection timeout (milliseconds)=30000
# Maximum number of connections in the connection pool (using negative values ​​to indicate no limit) Default 8-active=8
# Maximum idle connection in connection pool Default 8-idle=8
# Minimum idle connection in connection pool Default 0-idle=1
#Maximum free waiting time in the connection pool, directly expel the link when there is no work in 3 seconds-evicate-idle-time-millis=3000
# Maximum blocking waiting time for connection pool (using negative values ​​to indicate no limit) Default -1-wait=-1

3. Write a configuration class to solve the problem of garbled code and the real type of object

package ;

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

import ;

@Configuration
public class RedisConfig {
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate&lt;Object, Object&gt; redisTemplate(RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate&lt;Object, Object&gt; template = new RedisTemplate&lt;&gt;();
        (redisConnectionFactory);
        // Key serialization method        (StringRedisSerializer.UTF_8);
        //Jackson2JsonRedisSerializer serialization method is used to replace the original jdk serialization method, because the latter will be garbled.        Jackson2JsonRedisSerializer jack = new Jackson2JsonRedisSerializer();
        (jack);
        (StringRedisSerializer.UTF_8);
        (jack);
        /**
          * Use objeck to set the object's type to the real object type instead of hsash
          */
        ObjectMapper mapper=new ObjectMapper();
        // Enable default type inference and write type information as attributes to JSON        // It is to write the entire class name of the object to json        ((), .NON_FINAL);
         // Pass the type information as attribute to json        (mapper);
        return template;
    }
}

4. Code cases

4.1 model preparation because it is possible to store objects

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Student implements Serializable {
   private Integer id;
   private String name;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Product implements Serializable {
    private Integer id;
    private String name;
}

4.2 Use redis to operate string

@Slf4j
@SpringBootTest
class StringTest {
    /**
      * Use redis to operate string
      */
    @Autowired
    private StringRedisTemplate str;
    // Automatic serialization, use @Autowired to report an error    @Resource(name ="redisTemplate")
    private RedisTemplate&lt;String,Student&gt; redisTemplate;
    private  final  String key ="zhouxingxing";

    /**
      * Serialize the object without manually converting the object into a string
      */
    @Test
    void m8() {
        // jdk serialization        Student student = ().id(1).name("Zhang San").build();
//        JdkSerializationRedisSerializer serializer =new JdkSerializationRedisSerializer();
//        byte[] serialize = (student);
//        String s=new String(serialize);
        // s garbled code        ().set("student", student);
        Student student1 =  ().get("student");
        (());

    }
    /**
      * get set method in string
      */
    @Test
    void m1() {
        ().set("xiaolong", "Such cool");
        String xiaolong = ().get("xiaolong");
        ("xiaolong:{}", xiaolong);
    }

    /**
      * strlen method in string
      * append method: append string
      */
    @Test
    void m2() {
        ().set("xiaolong", "Such cool");
        String xiaolong = ().get("xiaolong");
        ("xiaolong:{}", xiaolong);
        // Append string        ().append("xiaolong", "Ha ha");
        // Get length        Long size = ().size("xiaolong");
        ("The length is:{}", size);//15
    }

    /**
      * incr method in string
      * incrBy method: increase the specified value
      */
    @Test
    void m3() {
        ().set("xiaolong", "100");
        Long xiaolong = ().decrement("xiaolong", 2);
        ("xiaolong:{}", xiaolong); //98
    }

    /**
      * Save the student object in redis
      * (Object) --->Convert the object into a serialized json string
      */
    @Test
    void m4() {
        Student student = ().id(1).name("Zhang San").build();
        ().set("student", (student));
        ("student:{}", ().get("student"));//student:{"id":1,"name":"Zhang San"}    }
    @Test
    public void m7() {
        ().put(key,"20220325","Zhengzhou");
        ().put(key,"20220326","Luoyang");
        // Get all the values ​​of small keys        List&lt;Object&gt; values = ().values(key);
        for (Object value : values) {
            (value);
        }
    }

4.3 Use redis to operate list

@SpringBootTest
@Slf4j
public class ListTest {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private final String key = "xiaolong";
    /**
      * Push the element left and push the element again to list
      * Delete the element from the right and return the deleted element
      */
    @Test
    void m1() {
        ().leftPush(key, "g1");
        ().leftPush(key, "g2");
        ().leftPush(key, "g3");
        ().rightPush(key, "g4");//The order is g3 g2 g1 g4        // Delete the element from the right and return the deleted element        String s = ().rightPop(key);
        ("Delete the element as:{}", s);// g4
    }

    @Test
    public void m2() {
        List&lt;Object&gt; obj = ((RedisCallback&lt;Object&gt;) connection -&gt; {
            //The queue has no elements and will block the operation until the queue gets a new element or timeout            return (600, "list1".getBytes());
        }, new StringRedisSerializer());
        for (Object str : obj) {
            (str);
        }
    }

4.4 Use redis to operate hash

@Slf4j
@SpringBootTest
public class HashTest {
    @Autowired
    private StringRedisTemplate redisTemplate;
    // Automatic serialization    @Resource(name ="redisTemplate")
    private RedisTemplate&lt;String, Student&gt; redisTemplate1;
    // Set a big key    private final String key = "xiaolong";
    @Test
     void m10() {
        Student student = ().id(1).name("Zhang San").build();
        ().put(key, "g1", student);
        Object o = ().get(key, "g1");
    }
 // Set up product blacklist    @Test
    public void m9() {
        Product p1 = ().id(1).name("Huawei").build();
        Product p2 = ().id(2).name("Millet").build();
        ().put("blacklist","List List 1",p1);
        ().put("blacklist","List List 2",p2);
    }

    /**
      * Get the values ​​of all small keys in the big key
      */
    @Test
    public void m1() {
        ().put(key, "g1", "Xiaofang");
        ().put(key, "g2", "Little Red");
        // Get all the values ​​of small keys        List&lt;Object&gt; values = ().values(key);
        for (Object value : values) {
            ("The values ​​of all small keys are:"+value);
        }
    }

4.5 Use redis operation set

@SpringBootTest
@Slf4j
public class SetTest {
  @Autowired
   private StringRedisTemplate redisTemplate;
   private final String xiaoming = "xiaoming";
   private final String xiaohong = "xiaohong";
  @Test// Intersection    void m1()
    {
        // Add subjects that Xiao Ming is interested in        ().add(xiaoming, "Chinese", "math","physics");
        // Add subjects that Xiaohong is interested in        ().add(xiaohong, "Chinese", "English");
        // Get subjects that two students are interested in        Set&lt;String&gt; tong = ().intersect(xiaohong, xiaoming);
        for (String s : tong) {
           ("The subjects that Xiao Ming and Xiao Hong are interested in are:"+s);// Chinese        }
    }
    @Test//Unit    void m2()
    {
        // Add subjects that Xiao Ming is interested in        ().add(xiaoming, "Chinese", "math","physics");
        // Add subjects that Xiaohong is interested in        ().add(xiaohong, "Chinese", "English");
        // Get subjects that two students are interested in        Set&lt;String&gt; tong = ().union(xiaohong, xiaoming);
        for (String s : tong) {
            ("The subjects that Xiao Ming and Xiao Hong are interested in are:"+s);// Chinese        }
    }

4.6 Use redis to operate zset

@SpringBootTest
@Slf4j
public class ZsetTest {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Resource(name = "redisTemplate")
    private RedisTemplate&lt;String, Integer&gt; redisTemplate1;
    private String key = "xiaolong";
    /**
      * zset ordered collection unique, deduplication suitable for today's headlines and hot searches
      * Add three points to Xiaolong to get results
      */
    @Test
    public void m1() {
        ().add(key, "Chinese", 90);
        ().add(key, "math", 100);
        ().add(key, "English", 80);
        Long aLong = ().zCard(key);
        ("{The number of subjects is:}", aLong);
        // Get the highest score of xiaolong. spring does not encapsulate it for us        (new RedisCallback&lt;Object&gt;() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                return (5, ());
            }
        });
    }

4.7 Redis Operation BitMap

@Component
public class BitMapDemo {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private final  String key ="sign#2022#zhouxingxing";
    public void test(){
       //Setting up sign-in        ().setBit(key,2,true);
        ().setBit(key,85,true);
        //Get the number of sign-in days of Zhou Xingxing        RedisCallback&lt;Long&gt; callback = connection -&gt; { return  ((),0,365);};
        Long count = (callback);
        //Print the number of sign-in days in 2022 by Zhou Xingxing        ("Zhou Xingxing's total number of sign-in days in 2022:"+count);
    }
}

Summarize

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