Spring boot 2.7.0 integrates redis (3)

What is Redis

Redis is a high-performance key-value storage system that supports String, list, set and other collections. In order to ensure reading efficiency, data is cached in memory.

Usually we will often need to read dictionary data, user login credential information, or concurrent data that requires high-speed processing can be read using redis to increase system performance and reduce server processing pressure.

The version and necessary conditions used in this tutorial

spring boot 2.7.0

Redis-x64-3.2.100.rar

Before using spring boot to connect to redis, first ensure that your redis service is running normally and can be connected using tools or commands. You can use the RedisDesktopManager graphical tool to connect and manage redis.

Create project

Create a new spring boot project. An empty project can be created via my previous tutorial.

Getting Started with Spring Boot

Edit pom file

After creating a new maven project in idea, you first need to introduce the following dependencies in the pom file.

Mainly includes: web dependency, redis dependency

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/>
    </parent>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

Don’t forget to reload the dependencies to prevent the jar package from being found! Click maven in turn, project name=》right click=》Reimport

Insert image description here

Directory Structure

Establish the package directory structure as shown below, the details are as follows:

Insert image description here

Configure redis service address

Modify the redis configuration in the application.properties configuration file. No password by default.

################ Redis ##############
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 链接超时时间 单位 ms(毫秒)
spring.redis.timeout=3000ms

Entity class

Write an entity class TestDataVO under the com.study.model package, which contains two fields: name and age, for testing reading and writing lists in redis. code show as below:

package com.study.model;

import java.io.Serializable;

public class TestDataVO implements Serializable {
    
    

    private String name;
    private int age;

    public TestDataVO(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }
}

Redis serializer LettuceRedisConfig

Edit the LettuceRedisConfig class under the com.study.config package. This class injects RedisTemplate into spring and sets the serializer for key and value. LettuceConnectionFactory is used here to obtain the connection. code show as below:

package com.study.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
 * LettuceRedis 配置文件
 * 设置序列化器
 */
@Configuration
public class LettuceRedisConfig {
    
    
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory connectionFactory) {
    
    
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(connectionFactory);
        return redisTemplate;
    }
}

Startup and testing class

Write the MyApplication class in com.study for spring boot startup and test data storage in redis. The code is as follows:

package com.study;
import com.study.model.TestDataVO;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@EnableAutoConfiguration
public class MyApplication {
    
    

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 测试接口 先将time存入redis 再从redis取出该值并返回
     * 38081是配置文件默认端口 可以在 application.properties中修改端口号
     * http://localhost:38081/addKey
     * @return
     */
    @RequestMapping("addKey")
    public Map<String, Object> addKey(){
    
    
        Map<String, Object> rsMap = new HashMap<>();
        long time = System.currentTimeMillis();
        String key = "time";
        //time 为key 存入 redis 2分钟后失效 不失效请取消后两个参数
        redisTemplate.opsForValue().set(key,time,2, TimeUnit.MINUTES);
        //将键为time的值取出 存入返回map
        rsMap.put("time", redisTemplate.opsForValue().get(key));
        return rsMap;
    }

    /**
     * 测试接口 将对象数组存入redis 从redis取出该值后返回
     * http://localhost:38081/addList
     * @return
     */
    @RequestMapping("addList")
    public Map<String, List<TestDataVO>> addList(){
    
    
        Map<String, List<TestDataVO>> rsMap = new HashMap<>();
        TestDataVO testDataVO = new TestDataVO("张三", 16);
        TestDataVO testDataVO1 = new TestDataVO("李四", 18);
        List<TestDataVO> list = new ArrayList<>();
        list.add(testDataVO);
        list.add(testDataVO1);
        //将集合存入到list中
        redisTemplate.opsForList().rightPushAll("testList", list);

        //从redis中取出数据
        List<TestDataVO> redisData = redisTemplate.opsForList().range("testList",0,-1);
        rsMap.put("testList", redisData);
        return rsMap;
    }

    /**
     * 测试接口 删除key
     * http://localhost:38081/addList
     * @return
     */
    @RequestMapping("removeKey")
    public Map<String, Object> removeKey(){
    
    
        Boolean rs = redisTemplate.delete("testList");
        Map<String, Object> rsMap = new HashMap<>();
        rsMap.put("rs", rs);
        return rsMap;
    }

    /**
     * 启动入口
     * @param args
     */
    public static void main(String[] args) {
    
    
        SpringApplication.run(MyApplication.class);
    }
}

test

Right-click to run the MyApplication class. Observe the console output as follows and observe that the project starts normally:

Insert image description here

Open the browser, enter the following address for interface testing, and select an interface to insert data into redis: http://localhost:38081/addKey

Insert image description here

Store the object array into redis and take out the interface: http://localhost:38081/addList

Delete key interface: http://localhost:38081/removeKey

Ok, spring boot integration with redis is basically completed.

write at the end

Open source is a virtue, join the open source community as soon as possible and build a beautiful ecosystem together!

Guess you like

Origin blog.csdn.net/qq_36378416/article/details/125873442