One, foreword

Redis is an in-memory database. What is an in-memory database? An in-memory database is relative to a hard disk database. Your computer is configured with 16GB memory and 500GB hard disk. Redis data is stored in 16GB memory and Mysql data is stored in 500GB hard disk.

Memory read and write speed is fast, so Redis database is fast, it can do cache and some high access rate data storage.

Because it is an in-memory database, Redis has a small storage capacity, and data will be lost when power is off. Therefore, Redis should not store large amounts of data. Redis has two persistence strategies for loss of power data (logging command and periodic flush), which will be discussed later.

Without further ado, SpringBoot integrates with Redis, directly on the code.

2. Directory structure and configuration

2.1 Directory Structure

2.2 the pom. XML


      
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2. RELEASE</version>
        <relativePath/> <! -- lookup parent from repository -->
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.llh</groupId>
    <artifactId>spring-boot-redis</artifactId>
    <version>1.0.0</version>
    <name>spring-boot-redis</name>
    <description>spring-boot-redis project description</description>

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

        <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>

</project>
Copy the code
  • That’s what I addedspring-boot-starter-data-redisRely on

2.3 application. The properties

Name =spring-boot-redis server.port=8888 # redis address spring.redis spring.redis.port=6379Copy the code
  • The main is redis address port configuration

Three, code,

RedisConfiguration class

package com.llh.springbootredis.config;

import org.springframework.beans.factory.annotation.Autowired;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/ * * *@author llh
 */
@Configuration
public class RedisConfiguration {
    private final RedisConnectionFactory redisConnectionFactory;

    @Autowired
    public RedisConfiguration(RedisConnectionFactory redisConnectionFactory) {
        this.redisConnectionFactory = redisConnectionFactory;
    }

    @Bean()
    public RedisTemplate<String, Object> redisTemplate(a) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(a) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
        returnstringRedisTemplate; }}Copy the code
  • The main thing here is injectionredisTemplatestringRedisTemplateobject
  • redisTemplateCan operate on objects, which configure the object serialization method
  • stringRedisTemplateCan only manipulate strings

The UserInfo class

package com.llh.springbootredis.bean;

import java.io.Serializable;

/ * * *@author llh
 */
public class UserInfo implements Serializable {
    private static final long serialVersionUID = -4514567603228180464L;

    private Long id;
    private String username;
    private String password;

    public UserInfo(Long id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Long getId(a) {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword(a) {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString(a) {
        return "UserInfo{" +
                "id=" + id +
                ", username='" + username + '\' ' +
                ", password='" + password + '\' ' +
                '} '; }}Copy the code
  • The entity class must be implementedSerializableInterface, because the object is serialized for saving

TestService class

package com.llh.springbootredis.service;

import com.llh.springbootredis.bean.UserInfo;

/ * * *@author llh
 */
public interface TestService {
    String test0(Long id);

    UserInfo test1(Long id);
}
Copy the code

TestServiceImpl class

package com.llh.springbootredis.service.impl;

import com.llh.springbootredis.bean.UserInfo;
import com.llh.springbootredis.service.TestService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/ * * *@author llh
 */
@Service
public class TestServiceImpl implements TestService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public String test0(Long id) {
        // Simulate delay operation
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Generate a new string");
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();

        String cacheKey = "str:" + id;
        System.out.println("Redis caches this string" + cacheKey + "= = = >" + str);
        stringRedisTemplate.opsForValue().set(cacheKey, str);
        return str;
    }

    @Override
    public UserInfo test1(Long id) {
        // Simulate delay operation
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Create a new object");
        UserInfo userInfo = new UserInfo(id, "admin"."123456");

        String cacheKey = "user:" + id;
        System.out.println("Redis caches this object" + cacheKey + "= = = >" + userInfo);
        redisTemplate.opsForValue().set(cacheKey, userInfo);
        returnuserInfo; }}Copy the code
  • stringRedisTemplate.opsForValue().set(cacheKey, str);Save data to Redis database.

TestController class

package com.llh.springbootredis.controller;

import com.llh.springbootredis.bean.UserInfo;
import com.llh.springbootredis.service.TestService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/ * * *@author llh
 */
@RestController
public class TestController {
    @Resource
    private TestService testService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("test0/{id}")
    public String test0(@PathVariable Long id) {
        // Query the cache
        String cacheKey = "str:" + id;
        String cacheVal = stringRedisTemplate.opsForValue().get(cacheKey);
        if(cacheVal ! =null) {
            System.out.println("Return string directly from redis cache");
            return cacheVal;
        }
        return testService.test0(id);
    }

    @GetMapping("test1/{id}")
    public UserInfo test1(@PathVariable Long id) {
        // Query the cache
        String cacheKey = "user:" + id;
        UserInfo cacheVal = (UserInfo) redisTemplate.opsForValue().get(cacheKey);
        if(cacheVal ! =null) {
            System.out.println("Return objects directly from redis cache");
            return cacheVal;
        }
        returntestService.test1(id); }}Copy the code
  • stringRedisTemplate.opsForValue().get(cacheKey)Get cached data.
  • The cache keys are all strings
  • Value of the cache,test0The interface is a stringtest1Interfaces are objects
  • Cache by ID. To distinguish the data type, the string Key is prefixed withstr:, the prefix of the object Key isuser:

Four, test,

  • localhost:8888/test0/1
  • localhost:8888/test0/2
  • localhost:8888/test1/1
  • localhost:8888/test1/2

  • It can be seen from the printed log that the same request is first to create a new object, and the second request is directly obtained from Redis, which is very fast.
  • The Redis database also has four pieces of data.

Five, the summary

Redis is probably by far the most used in-memory database, and there are a lot of fun things you can do with Redis data types in addition to caching. Such as distributed locks, like comments, etc. We’ve only used the simplest Key->String type here. It also has Key->List,Key->Map,Key->Set,Key->ZSet, etc.

GitHub source address: github.com/tigerleeli/…

Synchronize wechat official account: