Spring Cache基本使用

SpringCache是一个用于方法级别缓存的框架,支持通过不同缓存技术如EhCache、Guava和Redis进行缓存管理。@Cacheable、@CachePut、@CacheEvict等注解用于控制缓存的存取和清除。在SpringBoot项目中,可以通过配置Redis依赖和应用.yml文件来设置缓存,并在Controller中使用注解实现缓存操作。
摘要由CSDN通过智能技术生成

Spring Cache 介绍

Spring Cache 是一个框架。Spring Cache 是作用在方法上的,其核心思想是,当我们在调用一个缓存方法时会把该方法参数和返回结果作为一个键值对存在缓存中。

针对不同的缓存技术,需要实现不同的CacheManager。CacheManager是Spring提供的各种缓存管理技术的抽象接口

CacheManager描述
EhCacheCacheManager使用EhCach作为缓存管理技术
GuavaCacheManager使用Googe的GuavaCache作为缓存管理技术
RedisCacheManager使用Redis作为缓存管理技术

SpringCache常用注解

注解描述
@EnableCaching开启注解缓存功能,一般用在启动类上
@Cacheable在方法执行前,spring先查看缓存中是否有数据,如果没有数据,调用方法,并将方法返回值存入缓存中,如果有数据,则直接返回缓存中的数据
@CachePut从方法的返回值放入缓存中
@CacheEvict将一条或多条从缓存中删除
@Caching组合多个注解缓存

在springboot项目中,使用SpringCache的基本使用方式

配置

# 1. 导入相关依赖
<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>

# 2. 配置application.yml
spring
  redis:
    host: 192.168.160.100
    port: 6379
    password: root
    database: 0
  cache:
    redis:
      time-to-live: 1800000 #设置缓存过期时间,可选 单位毫秒

# 3. 在启动类上加上 @EnableCaching 注解,开启缓存注解功能

# 4. 在Controller的 方法 上使用 @Cacheable 、@CacheEvict

入门代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private UserService userService;

    /**
     * CachePut:将方法的返回值存入缓存
     * value:缓存的名字,每个缓存可以有多个key
     * key:缓存的key
     * condition:满足条件执行
     * unless:不满足条件执行
     * @param user
     * @return
     */
    @CachePut(value = "demo",key = "#user.id",unless ="#result == null" )
    @PostMapping("/save")
    public User save(User user){
        boolean save = userService.save(user);
        if (save) return user;
        else return null;
    }

    /**
     *CacheEvict:清理指定缓存,(根据value::key)
     * value:缓存的名称,一个缓存可以有多个key
     * key:缓存的key
     * condition:条件满足就执行缓存
     * @param id
     * @return
     */
    @CacheEvict(value = "demo",key = "#id",condition = "#result==true")
    @DeleteMapping("/{id}")
    public boolean del(Long id){
        return userService.removeById(id);
    }

    @CacheEvict(value = "demo",key = "#user.id")
    @PostMapping("/update")
    public boolean update(User user){
        return userService.updateById(user);
    }

    /**
     * Cacheable:先去缓存中,查询有没有数据,如果缓存中没有数据的话再访问数据库,将返回值存入缓存中
     * value:缓存的名称,一个缓存可以有多个key
     * @return
     */
    @Cacheable(value = "demo",key = "getMethodName()")
    @GetMapping("/list")
    public List<User> list(){
        return userService.list();
    }

}

详细注解及使用参数说明

Cacheable 先去缓存中查询,缓存中是否有对应的数据,如果没有再访问数据库,将返回值存入缓存中

参数描述使用
value缓存的名字。@CachePut(value=“demo”)
key缓存的key,可以为空。@CachePut(value = “demo”,key = “#user.id”)
condition缓存的条件。当返回值为true的时候才进行缓存。@CacheEvict(value = “demo”,key = “#id”,condition = “#result==true”)
unless缓存的条件。当返回值为true的时候就不进行缓存。@CachePut(value = “demo”,key = “#user.id”,unless =“#result == null” )

@CachePut 将返回值的内容存入缓存中

参数描述使用
value缓存的名字。@CachePut(value=“demo”)
key缓存的key,可以为空。@CachePut(value = “demo”,key = “#user.id”)
condition缓存的条件。当返回值为true的时候才进行缓存。@CacheEvict(value = “demo”,key = “#id”,condition = “#result==true”)
unless缓存的条件。当返回值为true的时候就不进行缓存。@CachePut(value = “demo”,key = “#user.id”,unless =“#result == null” )

CacheEvict 删除指定缓存中的内容

参数描述使用
value缓存的名字。@CachePut(value=“demo”)
key缓存的key,可以为空。@CachePut(value = “demo”,key = “#user.id”)
condition缓存的条件。当返回值为true的时候才进行缓存。@CacheEvict(value = “demo”,key = “#id”,condition = “#result==true”)
unless缓存的条件。当返回值为true的时候就不进行缓存。@CachePut(value = “demo”,key = “#user.id”,unless =“#result == null” )
allEntries是否清空所有缓存内容,如果设置true则代表清空,默认为false。@CacheEvict(value = “demo”,key = “#id”,condition = “#result==true”,allEntries = true)

@CacheConfig 类级别的注解

一次性声明 value

参数描述使用
cacheNames在这个注解声明的类下,在使用缓存注解中可以不用声明 value。如果声明了就以声明的为准@CacheConfig(cacheNames = “demos”)
import com.itheima.entity.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/demo")
@CacheConfig(cacheNames = "demos")
public class DemoController {

    @Autowired
    private UserService userService;

    /**
     * CachePut:将方法的返回值存入缓存
     * value:缓存的名字,每个缓存可以有多个key
     * key:缓存的key
     * condition:满足条件执行
     * unless:不满足条件执行
     * @param user
     * @return
     */
    @CachePut(key = "#user.id",unless ="#result == null" )
    @PostMapping("/save")
    public User save(User user){
        boolean save = userService.save(user);
        if (save) return user;
        else return null;
    }
}

@Caching 组合注解

显而易见,使用这个组件,可以配置多个注解

参数描述使用
cacheable查询缓存中是否有该数据,如果没有,则访问数据库,将返回值存入缓存中@Caching(cacheable={@Cacheable(…)})
put将返回值存入缓存中@Caching(put={@CachePut(…)})
evict指定清楚缓存@Caching(evict=@CacheEvict(…))

案列:

	// 只做参考。    
	@Caching(
            cacheable = {
                    @Cacheable(value = "test",key = "name001")
            },
            put = {
                    @CachePut(value = "put",key = "name0001")
            },
            evict = {
                    @CacheEvict(value = "evict",key = "name0001")
            }
    )
    public boolean test(){

        return false;
    }

基础使用的记录。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值