How to use Spring Data Redis in idea

How to use Spring Data Redis

1 Introduction

Spring Data Redis is a part of Spring. It provides access to Redis services through simple configuration in Spring applications and highly encapsulates the Redis underlying development package. In Spring projects, you can use Spring Data Redis to simplify Redis operations.

URL: https://spring.io/projects/spring-data-redis

Spring Boot provides the corresponding Starter, maven coordinates:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Spring Data Redis provides a highly encapsulated class: RedisTemplate, which classifies and encapsulates related APIs and encapsulates the same type of operations into operation interfaces. The specific classification is as follows:

  • ValueOperations: string data operations
  • SetOperations: set type data operations
  • ZSetOperations: zset type data operations
  • HashOperations: hash type data operations
  • ListOperations: list type data operations
2 Environment setup

Enter the sky-server module

1). Import the maven coordinates of Spring Data Redis (completed)

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2). Configure Redis data source

Add in application-dev.yml

sky:
  redis:
    host: localhost
    port: 6379
    password: 123456 #Redis password, if not available, you can comment it
    database: 10

Explanation:

database: Specify which database of Redis to use. After the Redis service is started, there are 16 databases by default, numbered from 0 to 15.

The number of databases can be specified by modifying the Redis configuration file.

Add the relevant Redis configuration in application-dev.yml to read in application.yml

spring:
  profiles:
    active:dev
  redis:
    host: ${<!-- -->sky.redis.host}
    port: ${<!-- -->sky.redis.port}
    password: ${<!-- -->sky.redis.password} #Redis password, if not available, you can comment it
    database: ${<!-- -->sky.redis.database}

3). Write configuration class and create RedisTemplate object

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Slf4j
public class RedisConfiguration {<!-- -->

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){<!-- -->
        log.info("Start creating redis template object...");
        //Create a RedisTemplate object
        RedisTemplate redisTemplate = new RedisTemplate();
        //Set the redis connection factory object
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //Set the serializer of redis key
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}

Explanation:

The current configuration class is not required because the Spring Boot framework will automatically assemble the RedisTemplate object, but the default key serializer is

JdkSerializationRedisSerializer causes the data we save in Redis to be different from the original data, so it is set to

StringRedisSerializer serializer.
4). Manipulate Redis through RedisTemplate object

Create a new test class under test

package com.sky.test;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;

@SpringBootTest
public class SpringDataRedisTest {<!-- -->
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testRedisTemplate(){<!-- -->
        System.out.println(redisTemplate);
        //string data operation
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //Hash type data operation
        HashOperations hashOperations = redisTemplate.opsForHash();
        //List type data operations
        ListOperations listOperations = redisTemplate.opsForList();
        //set type data operation
        SetOperations setOperations = redisTemplate.opsForSet();
        //zset type data operation
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
    }
}

test:

It means that the RedisTemplate object is injected successfully, and the related objects of five data types are obtained and operated through the RedisTemplate object.

After the above environment is set up, next, we will specifically operate on the five common data types.

3 Manipulate common types of data

1). Manipulate string type data

 /**
     * Manipulate string type data
     */
    @Test
    public void testString(){<!-- -->
        // set get setex setnx
        redisTemplate.opsForValue().set("name","Xiao Ming");
        String city = (String) redisTemplate.opsForValue().get("name");
        System.out.println(city);
        redisTemplate.opsForValue().set("code","1234",3, TimeUnit.MINUTES);
        redisTemplate.opsForValue().setIfAbsent("lock","1");
        redisTemplate.opsForValue().setIfAbsent("lock","2");
    }

2). Manipulate hash type data

 /**
     * Manipulate hash type data
     */
    @Test
    public void testHash(){<!-- -->
        //hset hget hdel hkeys hvals
        HashOperations hashOperations = redisTemplate.opsForHash();

        hashOperations.put("100","name","tom");
        hashOperations.put("100","age","20");

        String name = (String) hashOperations.get("100", "name");
        System.out.println(name);

        Set keys = hashOperations.keys("100");
        System.out.println(keys);

        List values = hashOperations.values("100");
        System.out.println(values);

        hashOperations.delete("100","age");
    }

3). Operation list type data

 /**
     * Manipulate list type data
     */
    @Test
    public void testList(){<!-- -->
        //lpush lrange rpop llen
        ListOperations listOperations = redisTemplate.opsForList();

        listOperations.leftPushAll("mylist","a","b","c");
        listOperations.leftPush("mylist","d");

        List mylist = listOperations.range("mylist", 0, -1);
        System.out.println(mylist);

        listOperations.rightPop("mylist");

        Long size = listOperations.size("mylist");
        System.out.println(size);
    }

4). Manipulate collection type data

 /**
     * Manipulate data of collection type
     */
    @Test
    public void testSet(){<!-- -->
        //sadd smembers scard sinter sunion srem
        SetOperations setOperations = redisTemplate.opsForSet();

        setOperations.add("set1","a","b","c","d");
        setOperations.add("set2","a","b","x","y");

        Set members = setOperations.members("set1");
        System.out.println(members);

        Long size = setOperations.size("set1");
        System.out.println(size);

        Set intersect = setOperations.intersect("set1", "set2");
        System.out.println(intersect);

        Set union = setOperations.union("set1", "set2");
        System.out.println(union);

        setOperations.remove("set1","a","b");
    }

5). Manipulate ordered set type data

 /**
     * Operate data of ordered collection type
     */
    @Test
    public void testZset(){<!-- -->
        //zadd zrange zincrby zrem
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();

        zSetOperations.add("zset1","a",10);
        zSetOperations.add("zset1","b",12);
        zSetOperations.add("zset1","c",9);

        Set zset1 = zSetOperations.range("zset1", 0, -1);
        System.out.println(zset1);

        zSetOperations.incrementScore("zset1","c",10);

        zSetOperations.remove("zset1","a","b");
    }

6). Common command operations

 /**
     * Common command operations
     */
    @Test
    public void testCommon(){<!-- -->
        //keys exists type del
        Set keys = redisTemplate.keys("*");
        System.out.println(keys);

        Boolean name = redisTemplate.hasKey("name");
        Boolean set1 = redisTemplate.hasKey("set1");

        for (Object key : keys) {<!-- -->
            DataType type = redisTemplate.type(key);
            System.out.println(type.name());
        }

        redisTemplate.delete("mylist");
    }

4. For example: such as the development of store business status

4.1 Management code

public class ShoppingController {<!-- -->

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String KEY = "SHOP_STATUS";
    /**
     * Set store status
     * @param status
     * @return
     */
    @PutMapping("/{status}")
    @ApiOperation("Set the business status of the store")
    public Result setStatus(@PathVariable Integer status){<!-- -->

        log.info("The business status of the store obtained is: {}", status == 1 ? "Business" : "Closing");
         //The redis storage method is key-value pair to set the business status of the store. If you want to retrieve the data, you need to provide the key value.
        redisTemplate.opsForValue().set(KEY,status);
        return Result.success();
    }
}

4.2 Client code

public class ShoppingController {<!-- -->

    @Autowired
    private RedisTemplate redisTemplate;

    public static final String KEY = "SHOP_STATUS";
    /**
     * Get the business status of the store
     * @return
     */
    @GetMapping("/status")
    @ApiOperation("Get the business status of the store")
    public Result<Integer> getStatus(){<!-- -->
        //Get the business status of the store through the key value stored on the management side
        Integer status = (Integer) redisTemplate.opsForValue().get(KEY);
        log.info("The business status of the store obtained is: {}", status == 1 ? "Business" : "Closing");

        return Result.success(status);
    }
}