笔记

万物寻其根,通其堵,便能解其困。
  博客园  :: 新随笔  :: 管理

spring boot中@Cache+redis的使用

Posted on 2024-05-31 17:35  草妖  阅读(10)  评论(0)    收藏  举报

参照详情连接地址:缓存之SpringCache整合redis(五)_spring中cache 和 redis 缓存-CSDN博客,如果需要查看请跳转查阅,本文仅作笔记记录。

案例代码:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <groupId>com.namejr</groupId>
    <artifactId>FirstSBDemo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.14</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.11</version>
        </dependency>
        <!-- 使用@Cacheable缓存处理 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.yml</include>
                    <include>**/*.xml</include>
                    <include>**/*.json</include>
                    <include>**/*.txt</include>
                    <include>**/*.mp3</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <!-- 注册webapp目录为资源目录 -->
                <directory>src/main/webapp</directory>
                <targetPath>META-INF/resources</targetPath>
                <includes>
                    <include>**/**</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <includeSystemScope>true</includeSystemScope>
                    <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
                </configuration>
            </plugin>
            <plugin>
                <!-- 配置jar包打包工具 -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <webResources>
                        <resource>
                            <directory>${project.basedir}/libs</directory>
                            <targetPath>WEB-INF/lib</targetPath>
                            <includes>
                                <include>**/*.jar</include>
                            </includes>
                        </resource>
                    </webResources>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

application.properties配置表

server.port=8080
logging.config=classpath:logback-spring.xml

# 配置@Cacheable缓存
# 表示使用redis
spring.cache.type=redis
# 是否缓存空值,开启可能造成缓存穿透问题
spring.cache.redis.cache-null-values=false
# 设置缓存过去时间60秒
spring.cache.redis.time-to-live=60000
# 添加前缀
spring.cache.redis.key-prefix=cache_
# 是否开启前缀(默认false时,spring.cache.redis.key-prefix无效)
spring.cache.redis.use-key-prefix=false

# 配置redis信息
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.database=8
PublicController.java控制器
注:
使用@cache缓存后,第一次或着删除(过期)缓存,否则将会一直显示的是缓存信息。
package com.namejr.controller;

import com.namejr.bean.UserModel;
import com.namejr.serviceImpl.PublicServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.alibaba.fastjson.JSON;

@RestController
@RequestMapping(value = "/api/public")
@Validated
// 开启缓存功能
@EnableCaching
public class PublicController {
    private Random _random=new Random();
    @Autowired
    private PublicServiceImpl pServiceImpl;

    @RequestMapping(value = "/getServerTime", method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    public String getServerTime() {
        return DateTime.now().toString("yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 添加缓存:@Cacheable(value = "list", key = "#index")
     * value:缓存的名称,"list" 表示集合名称。
     * key:缓存的 key。默认值为"",表示使用默认的 key 生成策略,这里"#index"中的index是参数。
     * condition:缓存的条件。默认值为"",表示不考虑任何条件,缓存所有结果。
     * unless:缓存的排除条件。默认值为"",表示不排除任何结果。
     * **/
    @RequestMapping(value = "/getCacheableDemo", method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @Cacheable(value = "list", key = "#index",condition = "#index>0")
    public List<String> getCacheableDemo(int index) {
        List<String> tempUserInfos=new ArrayList<>();
        UserModel tempUserInfo=new UserModel();
        tempUserInfo.userID=index;
        tempUserInfo.userName="namejr"+index+":"+_random.nextInt(1000000);
        // 注:不能使用List<UserModel>,需要转换为redis支持的几种类型:字符串、(字符串)列表、集合、有序集合、哈希表
        tempUserInfos.add(JSON.toJSONString(tempUserInfo));
        return tempUserInfos;
    }

    /**
     * 删除缓存:@CacheEvict 释义同上
     * */
    @RequestMapping(value = "/delCacheableDemo", method = RequestMethod.GET,produces = "application/json;charset=UTF-8")
    @CacheEvict(value = "list", key = "#index",condition = "#index>0")
    public String delCacheableDemo(int index) {
        return "delCacheableDemo...";
    }
}

 其余内容

@Cacheable:保存到缓存中。
@CacheEvict:删除缓存。
@CachePut:不影响方法执行,更新缓存。(双写模式默认)
@Caching:多条命令操作。
@CacheConfig:共享缓存配置(类级别)。

如果需要了解jedis的使用可以查看该博客:Spring boot中Redis的使用 - 闪电龟龟 - 博客园 (cnblogs.com)