Spring Cache

概念

  • 前面使用Spring boot整合的Redis使用Spring Data Redis进行操作,但是代码上还是很复杂,所以我们可以使用Spring Cache框架,对Spring Data Redis的操作进行简化。

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

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

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

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

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

常用注解:

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

使用

Spring Cache的Maven坐标

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

想要开启缓存注解开发,需要在boot的启动类上添加@EnableCaching注解

@SpringBootApplication
@EnableCaching
public class Application{
	public static void main(String[] args) {
		SpringApplication.run(Application.class,args);
	}
}

然后就可以在Controller相应的方法上添加注解。

添加缓存

在有新增缓存的业务需求时可以使用@CachePut

/**
*CachePut:将方法返回值放入缓存
*value:缓存的名称,每个缓存名称下可以有多个key
*key:缓存的key
*#result.id动态获得返回值的id
*/
@PostMapping
@CachePut(value = "userCache",key = "#result.id")
public User save(User user){
	userService.save(user);
	return user;
	//要将返回user同时添加到缓存中
}

清理缓存

使用@CacheEvict注解

/**
*此处`key`有很多中写法,意思都是一样的
*/
@CacheEvict(value = "userCache",key = "#id")
//CacheEvict(value = "userCache",key = "#p0")
//CacheEvict(value = "userCache",key = "#root.args[0]")
@DeleteMapping("/{id}")
public void deleteById(@PathVariable Long id){
	userService.removeById(id);
}

查询缓存

使用@Cacheable注解

/*
其中的condition是条件,满足条件时才缓存数据
key可以使用下划线来拼接例如"#user.id"+'_'+"#user.name"
*/
@Cacheable(value = "userCache",key = "#id",condition = "#result != null")
@GetMapping("/{id}")
public User getById(@PathVariable Long id){
	User user = userService.getById(id);
	return user;
}

总结

使用Redis缓存技术步骤:

  1. 导maven坐标
    导入spring-boot-starter-data-redis和
    spring-boot-starter-cache两个坐标
  2. 配置application.yml
spring:
	redis:
		host: 127.0.0.1
		port: 6379
		database: 0
	cache:
		redis:
			time-to-live: 1800000 #设置缓存有效期
  1. 在启动类添加@EnableCaching注解,开启缓存注解功能
  2. 在Controller的方法上加入@Cacheable、@CacheEvict等注解,及逆行缓存操作
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值