springboot 使用spring cache缓存 和 缓存数据落地到redis

springboot 使用spring cache缓存 和 缓存数据落地到redis

springboot工程已经和方便的支持缓存cache的使用了,几个注解就可以搞定。注意,这些缓存注解是基于spring容器环境的。

本文主要实现了:使用spring的 cache缓存功能,和将缓存数据落地到redis中

注解说明

// 放启动类上,开启缓存
@EnableCaching
// 放需要缓存的类上,统一设置缓存参数,简化配置@CachePut @Cacheable @CacheEvict
@CacheConfig:抽取类中的所有的公共配置

    
// 查询增加缓存 
@Cacheable:作用于查询方法上,查询接口继续缓存。

// 删除缓存
@CacheEvict:清除缓存,适用于删除方法上。

// 修改缓存
@CachePut:调用方法,又更新缓存数据,适合用于修改方法上,修改数据内容后缓存。

配置依赖

pom.xml文件配置maven依赖

<!-- spring boot 缓存 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

配置启动

启动类上加 @EnableCaching启用缓存

/**
 * @EnableCaching 开启springboot缓存
 */
@EnableCaching
@SpringBootApplication
public class SpaceAdminSystemApplication {

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

}

实例验证

package space.godchen.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * cache 演示
 * 一些缓存注解的属性说明
 * cacheNames/value:用来指定缓存组件的名字
 * key:缓存数据的key,同map的key。默认使用方法参数的值。
 * keyCenerator:key的生成器,key和keyGenerator二选一使用 不可同时使用,一般在key=“”里直接自己指定key就可以了。
 * condition:   符合指定的条件后才进行缓存操作
 * unless:  符合指定的条件后不缓存,不符合时缓存。同condition相反,也可以通过返回接口进行判断。使用#result 获取方法返回结果。
 * sync:是否使用异步模式。默认是方法执行完,以同步的方式将方法返回的结果存到缓存中。
 *
 * @author chenzhao
 * @create 2022-08-24 15:57
 * 类上设置后,相当于每个方法设置cacheNames
 * @CacheConfig(cacheNames = "test_cache")
 */
@Slf4j
@RestController
@RequestMapping("/cache")
public class TestSpringCacheController {

    /**
     * 查询,增加缓存
     *
     * @param id
     * @return
     */
    @GetMapping("/getValueById/{id}")
    @Cacheable(cacheNames = "test_cache", key = "#id")
    public String getValueById(@PathVariable Integer id) {
        String defaultValue = "默认的Value";
        log.info("默认的Value:{}", defaultValue);
        return defaultValue;
    }

    /**
     * 修改,更新缓存
     *
     * @param id
     * @param newValue
     * @return
     */
    @GetMapping("/putValueById/{id}/{newValue}")
    @CachePut(cacheNames = "test_cache", key = "#id")
    public String putValueById(@PathVariable Integer id, @PathVariable String newValue) {
        log.info("ID:{},对应的Value值,更新为:{}", id, newValue);
        return newValue;
    }

    /**
     * 删除, 清除缓存
     *
     * @param id
     * @return
     */
    @GetMapping("/evictValueById/{id}")
    @CacheEvict(cacheNames = "test_cache", key = "#id")
    public String evictValueById(@PathVariable Integer id) {
        log.info("删除ID:{}的缓存", id);
        return "" + id;
    }

}

springboot项目,使用spring cache 完成了。
下一步就是将缓存的数据,落地保存到redis中:

配置redis缓存

使用redis存放缓存数据

添加依赖

<!-- Spring boot Redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

启动本机redis,localhost:6379,

由于导入的maven依赖中,有redis的默认配置类,无需自己单独配置。

程序直接使用本机redis了。(此处redis未做详细配置,只要redis能用即可)

//spring-boot-starter-data-redis 包下的默认配置
package org.springframework.boot.autoconfigure.data.redis;

import java.time.Duration;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(
    prefix = "spring.redis"
)
public class RedisProperties {
    private int database = 0;
    private String url;
    private String host = "localhost";
    private String username;
    private String password;
    private int port = 6379;
    private boolean ssl;
    private Duration timeout;
    private Duration connectTimeout;
    private String clientName;
    private RedisProperties.ClientType clientType;
    private RedisProperties.Sentinel sentinel;
    private RedisProperties.Cluster cluster;
    private final RedisProperties.Jedis jedis = new RedisProperties.Jedis();
    private final RedisProperties.Lettuce lettuce = new RedisProperties.Lettuce();
    ...
}

哇塞,完成了,springboot对接redis缓存完成了。

此时,可以看到redis中的,key-value。 因为redis没有做系列化配置,此处value显示了乱码,忽略。 在这里插入图片描述

调用刚写的几个接口测试,就会发现缓存正常。

到这里,使用spring的 cache缓存功能,和将缓存数据落地到redis中,完成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Goldchenn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值