Spring Boot 结合Spring Cache三大注解(@Cacheable,@CachePut,@CacheEvict)做缓存使用

Spring Cache是一个框架,实现了基于注解的缓存功能,只需要简单地加一个注解,就能实现缓存功能,大大简化我们在业务中操作缓存的代码。

注解

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

使用
在spring boot项目中,使用缓存技术只需在项目中导入相关缓存技术的依赖包,并在启动类上使用**@EnableCaching**开启缓存支持即可。
例如,使用Redis作为缓存技术,只需要导入Spring data Redis的maven坐标即可。

使用步骤:

引导类上加**@EnableCaching**
在引导类上加该注解,就代表当前项目开启缓存注解功能。

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

集成Redis
导入坐标

<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>

application.yml做配置

spring:
  redis:
    host: 192.168.200.200
    port: 6379
    # password: root@123456(有设置密码,使用)
    database: 0
  cache:
    redis:
      time-to-live: 1800000   #设置缓存过期时间,可选

@CachePut注解

@CachePut 说明: 
	作用: 将方法返回值,放入缓存
	value: 缓存的名称, 每个缓存名称下面可以有很多key
	key: 缓存的key  ----------> 支持Spring的表达式语言SPEL语法

1). 在save方法上加注解@CachePut

当前UserController的save方法是用来保存用户信息的,我们希望在该用户信息保存到数据库的同时,也往缓存中缓存一份数据,我们可以在save方法上加上注解 @CachePut,用法如下:

/**
* CachePut:将方法返回值放入缓存
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
*/
@CachePut(value = "userCache", key = "#user.id")
@PostMapping
public User save(User user){
    userService.save(user);
    return user;
}
key的写法如下: 
	#user.id : #user指的是方法形参的名称, id指的是user的id属性 , 也就是使用user的id属性作为key ;
	#user.name: #user指的是方法形参的名称, name指的是user的name属性 ,也就是使用user的name属性作为key ;
	#result.id : #result代表方法返回值,该表达式 代表以返回对象的id属性作为key ;
	#result.name : #result代表方法返回值,该表达式 代表以返回对象的name属性作为key ;

@CacheEvict注解

@CacheEvict 说明: 
	作用: 清理指定缓存
	value: 缓存的名称,每个缓存名称下面可以有多个key
	key: 缓存的key  ----------> 支持Spring的表达式语言SPEL语法

1). 在 delete 方法上加注解@CacheEvict
当我们在删除数据库user表的数据的时候,我们需要删除缓存中对应的数据,此时就可以使用@CacheEvict注解, 具体的使用方式如下:

/**
* CacheEvict:清理指定缓存
* value:缓存的名称,每个缓存名称下面可以有多个key
* key:缓存的key
*/
@CacheEvict(value = "userCache",key = "#p0")  //#p0 代表第一个参数
//@CacheEvict(value = "userCache",key = "#root.args[0]") //#root.args[0] 代表第一个参数
//@CacheEvict(value = "userCache",key = "#id") //#id 代表变量名为id的参数
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id){
    userService.removeById(id);
}

在 update 方法上加注解@CacheEvict
在更新数据之后,数据库的数据已经发生了变更,我们需要将缓存中对应的数据删除掉,避免出现数据库数据与缓存数据不一致的情况。

//@CacheEvict(value = "userCache",key = "#p0.id")   //第一个参数的id属性
//@CacheEvict(value = "userCache",key = "#user.id") //参数名为user参数的id属性
//@CacheEvict(value = "userCache",key = "#root.args[0].id") //第一个参数的id属性
@CacheEvict(value = "userCache",key = "#result.id")         //返回值的id属性
@PutMapping
public User update(User user){
    userService.updateById(user);
    return user;
}

@Cacheable注解

@Cacheable 说明:
	作用: 在方法执行前,spring先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放到缓存中
	value: 缓存的名称,每个缓存名称下面可以有多个key
	key: 缓存的key  ----------> 支持Spring的表达式语言SPEL语法

在getById上加注解@Cacheable

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

缓存非null值

在@Cacheable注解中,提供了两个属性分别为: condition, unless 。
condition : 表示满足什么条件, 再进行缓存 ;
**unless : 表示满足条件则不缓存 ; 与上述的condition是反向的 ;**(推荐)
/**
 * 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;
}

在list方法上加注解@Cacheable
在list方法中进行查询时,有两个查询条件,如果传递了id,根据id查询; 如果传递了name, 根据name查询,那么我们缓存的key在设计的时候,就需要既包含id,又包含name。 具体的代码实现如下:

@Cacheable(value = "userCache",key = "#user.id + '_' + #user.name")
@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;
}

第一次查询时,需要查询数据库,在后续的查询中,就直接查询了缓存,不再查询数据库了。

案例:
@CacheEvict(value = “setmealCache”,allEntries = true) //清除setmealCache名称下,所有的缓存数据

好的,下面是一个使用Spring Boot整合Redis的`@Cacheable`、`@CachePut`、`@CacheEvict`注解实现增删改查的示例: 1. 添加Redis依赖 在pom.xml中添加以下依赖: ```xml <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. 配置Redis连接 在application.properties中添加以下配置: ```properties # Redis连接配置 spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= # 开启缓存 spring.cache.type=redis ``` 3. 编写Redis配置类 ```java import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.lang.reflect.Method; import java.util.Arrays; @Configuration @EnableCaching public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // key序列化方式 RedisSerializer<String> stringRedisSerializer = new StringRedisSerializer(); redisTemplate.setKeySerializer(stringRedisSerializer); // key redisTemplate.setHashKeySerializer(stringRedisSerializer); // hash key // value序列化方式 RedisSerializer<Object> valueRedisSerializer = new GenericJackson2JsonRedisSerializer(); redisTemplate.setValueSerializer(valueRedisSerializer); // value redisTemplate.setHashValueSerializer(valueRedisSerializer); // hash value redisTemplate.afterPropertiesSet(); return redisTemplate; } @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory); return builder.build(); } @Bean public KeyGenerator wiselyKeyGenerator() { return (Object target, Method method, Object... params) -> { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); Arrays.stream(params).forEach(param -> sb.append(param.toString())); return sb.toString(); }; } } ``` 4. 编写实体类 ```java import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = 1L; private Integer id; private String name; private Integer age; public User(Integer id, String name, Integer age) { this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } } ``` 5. 编写Service ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserDao userDao; @Cacheable(value = "user", keyGenerator = "wiselyKeyGenerator") public User getUserById(Integer id) { return userDao.getUserById(id); } @CachePut(value = "user", keyGenerator = "wiselyKeyGenerator") public User updateUser(User user) { userDao.updateUser(user); return user; } @CacheEvict(value = "user", keyGenerator = "wiselyKeyGenerator") public void deleteUserById(Integer id) { userDao.deleteUserById(id); } } ``` 6. 编写Controller ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User getUserById(@PathVariable Integer id) { return userService.getUserById(id); } @PutMapping("") public User updateUser(@RequestBody User user) { return userService.updateUser(user); } @DeleteMapping("/{id}") public void deleteUserById(@PathVariable Integer id) { userService.deleteUserById(id); } } ``` 7. 测试 启动应用后,可以通过以下方式测试: - 获取用户:GET http://localhost:8080/user/1 - 更新用户:PUT http://localhost:8080/user 请求体: ```json { "id": 1, "name": "Tom", "age": 20 } ``` - 删除用户:DELETE http://localhost:8080/user/1 以上就是一个使用Spring Boot整合Redis的`@Cacheable`、`@CachePut`、`@CacheEvict`注解实现增删改查的示例。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

最好的期待,未来可期

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

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

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

打赏作者

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

抵扣说明:

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

余额充值