三十三 SpringBoot整合@CacheEvict注解使用

 CacheEvict作用:清除缓存

UsersServiceImpl.java

	@Override
	@Cacheable(value="users")
	public List<Users> findUserAll() {
		return usersRepository.findAll();
	}

	@Override
	// @CacheEvict(value="users", allEntries=true)表示清除缓存中以users缓存策略缓存中的对象
	@CacheEvict(value="users", allEntries=true)
	public void saveUsers(Users user) {
		usersRepository.save(user);
	}

UsersServiceTest.java

	/**
	 * 1.不加缓存注解,两次查询会查两次,如下:
Hibernate: select users0_.id as id1_3_, users0_.address as address2_3_, users0_.age as age3_3_, users0_.name as name4_3_, users0_.role_id as role_id5_3_ from t_users users0_
[Users [id=1, name=guozi, age=18, address=地球]]
Hibernate: select users0_.id as id1_3_, users0_.address as address2_3_, users0_.age as age3_3_, users0_.name as name4_3_, users0_.role_id a
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值