springboot中redis缓存的基本使用

springboot中redis缓存的基本使用

一、使用

1、依赖引入

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

2、启动类添加@EnableCaching注解

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

3、yml文件中添加redis连接信息

spring:
  redis:
    host: localhost
    port: 6379
    password: 1234

4、编写缓存配置类

@Configuration
@EnableCaching
public class CacheConfig {
​
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        return new LettuceConnectionFactory();
    }
    
    @Bean
    public CacheManager cacheManager() {
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .disableCachingNullValues()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
    
        RedisCacheManager redisCacheManager = RedisCacheManager.builder(redisConnectionFactory())
                .cacheDefaults(redisCacheConfiguration)
                .build();
    
        return redisCacheManager;
    }
​
}

5、编写对应的缓存服务

@Service
public class CacheService {
​
    @Cacheable(cacheNames = "CacheData", key = "#id", unless = "#result == null")
    public String getCacheData(Integer id, String data) {
        // 模拟数据库查询或其他耗时操作
        Thread.sleep(1000);
        return  id + "    " + data;
    }
    
    @CachePut(cacheNames = "CacheData", key = "#id", unless = "#result == null")
    public String updateCacheDate(Integer id, String data) {
        return  id + "    " + data;
    }
    
    @CacheEvict(cacheNames = "CacheData", key = "#id")
    public String removeCacheData(Integer id) {
        return  "remove success";
    }
​
}

6、编写controller进行测试

  • @Cacheable

    该注解可以将方法运行的结果进行缓存,在缓存时效内再次调用该方法时不会调用方法本身,而是直接从缓存获取结果并返回给调用方。

    编写controller进行测试

        @Autowired
        CacheService cacheService;
        @GetMapping("/getCacheData")
        public String getCacheData(@RequestParam Integer id, String data) throws InterruptedException {
            return cacheService.getCacheData(id,data);
        }

    第一次请求响应时间1628ms

    第二次请求响应时间22ms

    查看redis中的数据 redis中存储的是 return 之后的数据

  • @CachePut

    使用 @CachePut 注解标注的方法,在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式写入指定的缓存中。@CachePut 注解一般用于更新缓存数据

    编写controller进行测试

    @GetMapping("/updateCacheData")
    public String updateCacheData(@RequestParam Integer id, String data) throws InterruptedException {
        return cacheService.updateCacheDate(id,data);
    }

    缓存中的数据已经被更新

  • @CacheEvict

    @CacheEvict 注解的方法在被调用时,会从缓存中移除已存储的数据。

    编写controller进行测试

    @GetMapping("/removeCacheData")
        public String removeCacheData(@RequestParam Integer id){
            return cacheService.removeCacheData(id);
        }

    缓存已经被移除

二、属性

@Cacheable

属性名类型说明默认值
valueString[]指定缓存名称,支持多个名称{}
cacheNamesString[]value,指定缓存名称{}
keyString用于缓存的key的SpEL表达式""
keyGeneratorString指定用于生成缓存key的组件名""
cacheManagerString指定用于获取缓存的CacheManager的Bean名称""
cacheResolverString指定用于解析缓存名称的CacheResolver的Bean名称""
conditionString缓存条件,使用SpEL表达式,当表达式结果为true时缓存方法结果""
unlessStringcondition相反,当表达式结果为true时不缓存方法结果""
syncboolean是否等待缓存操作完成false

@CacheEvict

属性名类型说明默认值
valueString[]指定缓存名称,支持多个名称,使用逗号分隔{}
cacheNamesString[]value,指定缓存名称{}
keyString用于缓存的key的SpEL表达式""
keyGeneratorString指定用于生成缓存key的组件名""
cacheManagerString指定用于获取缓存的CacheManager的Bean名称""
cacheResolverString指定用于解析缓存名称的CacheResolver的Bean名称""
conditionString缓存条件,使用SpEL表达式,仅当表达式结果为true时清除缓存""
allEntriesboolean是否清除所有缓存项false
beforeInvocationboolean是否在方法调用之前清除缓存false

@CachePut

属性名类型说明默认值
valueString[]指定缓存名称,支持多个名称,使用逗号分隔{}
cacheNamesString[]value,指定缓存名称{}
keyString用于缓存的key的SpEL表达式""
keyGeneratorString指定用于生成缓存key的组件名""
cacheManagerString指定用于获取缓存的CacheManager的Bean名称""
cacheResolverString指定用于解析缓存名称的CacheResolver的Bean名称""
conditionString缓存条件,使用SpEL表达式,仅当表达式结果为true时更新缓存""
unlessStringcondition相反的条件,当表达式结果为true时不更新缓存""

  • 11
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值