Spring Boot Cache Actual Redis

Spring boot uses SimpleCacheConfiguration by default, even using Concurrent MapCache Manager to implement caching. But switching to other cache implementations is also simple. The following is the use of redis as a cache:

pom file

Introducing corresponding jar packages into pom







configuration file

In the application.properties file, configure redis, databases, etc.

# Data source configuration

# JPA configuration
#Hibernate provides the function of automatically maintaining database table structure according to entity class. It can be configured by spring.jpa.hibernate.ddl-auto. There are the following options:
#1. create: Delete the last generated table at startup, and generate the table according to the entity class. The data in the table will be emptied.
#2. create-drop: At startup, tables are generated based on entity classes, and tables are deleted when session Factory closes.
#3. update: tables are generated based on entity classes at startup, and table structures are updated when attributes of entity classes change. This option is used in the initial development stage.
#4. validate: Verify the consistency of entity classes and data tables at startup, and use this option when our data structure is stable.
#5. none: No measures are taken.
#spring.jpa.show-sql is used to set up the hibernate operation and display its real SQL statement in the console.
#Make the json string format of the controller output more beautiful.

#Cache configuration
#Switching cache

#redis configuration
#database name
#server host
#server password
#connection port


Spring Boot automatically configures the Bean of RedisCache Manager for us.

Key Service

package com.xiaolyuh.service.impl;

import com.xiaolyuh.entity.Person;
import com.xiaolyuh.repository.PersonRepository;
import com.xiaolyuh.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

public class PersonServiceImpl implements PersonService {
    PersonRepository personRepository;

    @CachePut(value = "people", key = "#person.id")
    public Person save(Person person) {
        Person p = personRepository.save(person);
        System.out.println("by id,key by:" + p.getId() + "Data is cached");
        return p;

    @CacheEvict(value = "people")//2
    public void remove(Long id) {
        System.out.println("Deleted id,key by" + id + "Data caching");
        //No actual deletion is done here.

    @Cacheable(value = "people", key = "#person.id")//3
    public Person findOne(Person person) {
        Person p = personRepository.findOne(person.getId());
        System.out.println("by id,key by:" + p.getId() + "Data is cached");
        return p;


package com.xiaolyuh.controller;

import com.xiaolyuh.entity.Person;
import com.xiaolyuh.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

public class CacheController {

    PersonService personService;

    CacheManager cacheManager;

    public long put(@RequestBody Person person) {
        Person p = personService.save(person);
        return p.getId();

    public Person cacheable(Person person) {
        return personService.findOne(person);

    public String evit(Long id) {

        return "ok";


Startup class

@EnableCaching// Open the cache and specify what needs to be displayed
public class SpringBootStudentCacheApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootStudentCacheApplication.class, args);

Test class

package com.xiaolyuh;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import net.minidev.json.JSONObject;

public class SpringBootStudentCacheApplicationTests {

    public void contextLoads() {

    private MockMvc mockMvc; // The MVC object is simulated and initialized by MockMvcBuilders.webAppContextSetup(this.wac).build().

    private WebApplicationContext wac; // Injecting Web Application Context  

//    @Autowired  
//    private MockHttpSession session; // injection of simulated http session  
//    @Autowired  
//    private MockHttpServletRequest request; //Inject simulated http request\  

    @Before // Initialize work before testing starts  
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

    public void testAble() throws Exception {
        for (int i = 0; i < 2; i++) {
            MvcResult result = mockMvc.perform(post("/able").param("id", "2"))
                    .andExpect(status().isOk())// Simulate sending get requests to testRest
                    .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// The media type text/plain of the expected return value;
                    // charset=UTF-8
                    .andReturn();// Returns the result of executing the request



Print log

From the above, we can see that the first time to go is the database, and the second time to go is the cache.

View the Redis Library

Source code: https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases

spring-boot-student-cache-redis project

Laying-cache, a multi-level caching framework for monitoring This is an implementation of my open source multi-level caching framework. If you are interested, take a look at it.

Tags: Programming Spring Redis MySQL Hibernate

Posted on Mon, 07 Oct 2019 08:41:03 -0700 by novice_php