Spring Cache简单入门

1.Spring Cache介绍

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

Spring Cache提供了一层抽象,底层可以切换不同的cache实现。具体就是通过CacheManager接口来统一不同的缓存技术。

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

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

CacheManager

描述

EhCacheCacheManager

使用EhCache作为缓存技术

GuavaCacheManager

使用Google的GuavaCache作为缓存技术

RedisCacheManager

使用Redis作为缓存技术

2.Spring Cache常用注解

注解

说明

@EnableCaching

开启缓存注解功能

@Cacheable

在方法执行前spring先查看缓存中是否有数据,

如果有数据,则直接返回缓存数据;

若没有数据,调用方法并将方法返回值放到缓存中

@CachePut

将方法的返回值放到缓存中

@CacheEvict

将一条或多条数据从缓存中删除

在spring boot项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用@EnableCaching开启缓存支持即可。

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

<!--redis缓存和cache注解-->
        <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>

Spring自带的Cache(spring-boot-starter-web包含了)

(1)保存@CachePut(value="",key="#user.id")或者#result

注:此时缓存是在内存中


(2)移除@CacheEvict(value = "userCache",key = "#id") 或者 #root.args[ i ] 或者 #pi

 i 指的是形参数组的索引

(3)条件保存@Cacheable(value = "userCache",key = "#id",unless = "#result == null")

condition:条件,满足则缓存 (condition里无法使用#result)

unless:反条件,满足则不缓存

3.Spring Cache 使用方式

Spring Boot项目中使用Spring Cache的操作步骤(使用redis缓存技术)

1、导入maven坐标

  spring-boot-starter-data-redis、spring-boot-starter-cache

2配置application.yml

spring:
    cache:
        redis:
          time-to-live: 1800000 #缓存有效期30分钟

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

4、在Controller的方法上加入@Cacheable、@CacheEvict等注解,进行缓存操作

4.Spring Cache 上下文数据

 具体使用各个注解存在差异

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值