Spring Cache 介绍及使用方法

目录

一、Spring Cache介绍

1、Spring Cache常用注解

二、Spring Cache使用redis缓存步骤

1、添加依赖

2、添加配置

3、使用注解


一、Spring Cache介绍

Spring cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存

功能。Spring Cache提供了一层抽象,底层可以切换不同的cache实现。具体就是CacheManager

接口来统一不同的缓存技术。

CacheManager是Spring提供的各种缓存技术抽象接口。

针对不同的缓存技术需要实现不同的CacheManager:
 

CacheManager描述
EhcachecacheManager使用EhCache作为缓存技术
GuavaCacheManager使用Google的GuavaCache作为缓存技术
RedisCacheManager使用Redis作为缓存技术

1、Spring Cache常用注解

注解说明
@EnableCaching开启缓存注解功能
@Cacheable在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据若没有数据,调用方法并将方法返回值放到缓存中
@CachePut将方法的返回值放到缓存中
@CacheEvict将一条或多条数据从缓存中删除

在spring boot项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用

@EnableCaching开启缓存支持即可。

例如,使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可。

二、Spring Cache使用redis缓存步骤

1、添加依赖

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

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

2、添加配置

spring
  redis:
    host: 172.17.2.94  #ip地址
    port: 6379         #端口
    password: root@123456  #redis密码
    database: 0        #指定数据库
  cache:
    redis:
      time-to-live: 1800000 #设置缓存过期时间,可选

3、使用注解

启动类加注解:@EnableCaching

@Slf4j
@SpringBootApplication
@EnableCaching
public class CacheDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheDemoApplication.class,args);
        log.info("项目启动成功...");
    }
}

注解 @CachePut:将方法返回值放入缓存

    /**
     * CachePut:将方法返回值放入缓存
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     */
    //@CachePut(value = "userCache",key = "#result.id")//result带表返回值
    @CachePut(value = "userCache",key = "#user.id")//可以直接获取参数,参数名要保持一致
    @PostMapping
    public User save(User user){
        userService.save(user);
        return user;
    }

 key支持Spring的表达式语言,可以动态计算key值,通过#来获取,通常使用直接#+参数

result:表示返回值,可以通过获取返回值获取key

 

 userCache表示这一类缓存,缓存对象的key为id,缓存的值为一个对象



 

注解 @CacheEvict:清理指定缓存

    /**
     * CacheEvict:清理指定缓存
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     */
    @CacheEvict(value = "userCache",key = "#p0")//p固定写法,0表示下表,第一个参数
    //@CacheEvict(value = "userCache",key = "#root.args[0]")//固定写法,0表示下表,第一个参数
    //@CacheEvict(value = "userCache",key = "#id")//直接获取参数
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id){
        userService.removeById(id);
    }
    //@CacheEvict(value = "userCache",key = "#p0.id")//p0第一个参数,id参数的属性
    //@CacheEvict(value = "userCache",key = "#user.id")//直接获取参数属性
    //@CacheEvict(value = "userCache",key = "#root.args[0].id")//获取第一个参数,id参数的属性
    @CacheEvict(value = "userCache",key = "#result.id")//从返回值获取
    @PutMapping
    public User update(User user){
        userService.updateById(user);
        return user;
    }

注解 @Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据若没有数据,调用方法并将方法返回值放到缓存中

/**
     * Cacheable:在方法执行前spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
     * value:缓存的名称,每个缓存名称下面可以有多个key
     * key:缓存的key
     * condition:条件,满足条件时才缓存数据
     * unless:满足条件则不缓存
     */
    @Cacheable(value = "userCache",key = "#id",unless = "#result == null")
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id){
        User user = userService.getById(id);
        return user;
    }

    @Cacheable(value = "userCache",key = "#user.id + '_' + #user.name")//动态拼接key
    @GetMapping("/list")
    public List<User> list(User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user.getId() != null,User::getId,user.getId());
        queryWrapper.eq(user.getName() != null,User::getName,user.getName());
        List<User> list = userService.list(queryWrapper);
        return list;
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring CacheSpring框架提供的一种缓存机制,用于提高应用程序的性能和响应速度。通过使用Spring Cache,可以将方法的返回值缓存起来,当下次调用相同的方法时,可以直接从缓存中获取结果,而不需要再执行方法的逻辑。 在使用Spring Cache时,需要进行一些配置。首先,需要添加Redis的配置信息,包括缓存类型、缓存过期时间、缓存键的前缀等。可以通过设置`spring.cache.type`为`redis`来指定使用Redis作为缓存类型。可以使用`spring.cache.redis.time-to-live`设置缓存的过期时间,单位为毫秒。可以使用`spring.cache.redis.key-prefix`设置缓存键的前缀,如果不指定前缀,则默认使用缓存的名字作为前缀。可以使用`spring.cache.redis.use-key-prefix`设置是否使用前缀,默认为true。可以使用`spring.cache.redis.cache-null-values`设置是否缓存空值,以防止缓存穿透。 另外,Spring Cache还支持使用JCache(JSR-107)注解来简化开发。从Spring 3.1开始,定义了`org.springframework.cache.Cache`和`org.springframework.cache.CacheManager`接口来统一不同的缓存技术。 在使用Spring Cache时,可以通过在方法上添加`@Cacheable`注解来启用缓存功能。当调用带有`@Cacheable`注解的方法时,Spring会首先检查缓存中是否存在相应的结果,如果存在,则直接返回缓存中的结果,如果不存在,则执行方法的逻辑,并将结果存入缓存中。 总结起来,使用Spring Cache可以通过配置Redis等缓存信息,并在方法上添加`@Cacheable`注解来实现缓存功能,提高应用程序的性能和响应速度。 #### 引用[.reference_title] - *1* [SpringCache使用](https://blog.csdn.net/ABestRookie/article/details/121297482)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [springcache使用详解(使用redis做分布式缓存)](https://blog.csdn.net/A_art_xiang/article/details/125580962)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值