SpringBoot JPA 添加Redis缓存

SpringBoot JPA 添加Redis缓存

摘要

SpringBoot JPA 添加Redis缓存

springboot cache

springboot jpa查询数据库可以通过spring-boot-cache添加缓存的功能.
实现过程主要是在JPA Repository方法上添加注解.

@Cacheable(value = "users")
users会作为key的一部分. users:xxxxxxx
查询如果不在缓存中就查询db,然后保存到缓存,如果存在缓存中就直接返回.

@CachePut(value = "user_save")
@CacheEvict(value = {"users"}, allEntries = true)
CachePut跟Cacheable的区别是,前者是肯定会执行对缓存的更新.
这里又增加了一个注解CacheEvict,表示save方法被调用的时候肯定还会删除users:开头的所有的缓存 .

@CacheEvict(value = {"user_save", "users"}, allEntries = true)
这个也很好理解,当调用deleteAllInBatch的时候,所有的缓存都删除.

注解示例

package net.javablog;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface UserRepository extends JpaRepository<User, Long> {


    @Cacheable(value = "users")
    List<User> findAll();


    /**
     * 直接更新缓存 , 主要用于新增或更新方法  ,  单个item有更新的时候也要触发list的失效.
     */
    @CachePut(value = "user_save")
    @CacheEvict(value = {"users"}, allEntries = true)
    User save(User user);


    /**
     * 清空缓存  , value多个参数的时候,需要设置 allEntries =true
     */
    @CacheEvict(value = {"user_save", "users"}, allEntries = true)
    void deleteAllInBatch();


}

测试方法

package net.javablog;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nutz.json.Json;
import org.nutz.lang.random.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;


@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AppTest {


    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CacheManager cacheManager;

    @Before
    public void before() {
//        userRepository.deleteAllInBatch();
//        userRepository.save(new User("AAA", 10));
    }


    @Test
    public void test() throws Exception {


        //  org.springframework.data.redis.cache.RedisCacheManager
        System.out.println(cacheManager.getClass().getName());



        //第一次没有缓存
        List<User> users = userRepository.findAll();
        System.out.println("第1次查询:" + Json.toJson(users));

        List<User> users2 = userRepository.findAll();
        System.out.println("第2次查询:" + Json.toJson(users2));


        //缓存会新增1条记录 , 比如
        userRepository.save(new User(R.UU16(), 10));



        userRepository.deleteAllInBatch();

        System.out.println("over");


    }

}

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>net.javablog</groupId>
    <artifactId>jpawithrediscache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jpawithrediscache</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</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-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>


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


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>

        <dependency>
            <groupId>org.nutz</groupId>
            <artifactId>nutz</artifactId>
            <version>1.r.62</version>
        </dependency>

    </dependencies>


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

</project>

代码地址

https://github.com/daodaovps/testJpaWithRedisCache