SpringBoot 2.X @Cacheable,redis-cache 如何根据key设置缓存时间(二)

12 篇文章 0 订阅 ¥19.90 ¥99.00

参考(一)

@Configuration
public class RedisCacheConfig {
    @Value("${liu.globalSessionTimeout}")
    private long globalSessionTimeout;
    @Autowired
    ResourceLoader resourceLoader;
    
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        return RedisCacheManager.builder(redisConnectionFactory)
                //默认的缓存配置(没有配置键的key均使用此配置)
                .cacheDefaults(getDefaultCacheConfiguration())
                .withInitialCacheConfigurations(getCacheConfigurations())
                //在spring事务正常提交时才缓存数据
                .transactionAware()
                .build();
    }
    
    private Map<String, RedisCacheConfiguration> getCacheConfigurations() {
        Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>();
        //缓存键,且3600*10秒后过期,3600*10秒后再次调用方法时需要重新缓存
        configurationMap.put("AllMenuList",
  • 0
    点赞
  • 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
发出的红包

打赏作者

DN金猿

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

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

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

打赏作者

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

抵扣说明:

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

余额充值