Spring cache整合redis代码实例

 更新时间:2020年04月28日 11:50:17   作者:Terry  
这篇文章主要介绍了Spring cache整合redis代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

Spring-Cache是Spring3.1引入的基于注解的缓存技术,本质上它并不是一个具体的缓存实现,而是一个对缓存使用的抽象,通过Spring AOP技术,在原有的代码上添加少量的注解来实现将这个方法转成缓存方法的效果。

本来想来个分析源码,奈何水平有限,先从实战搞起。

先引入依赖:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
  <version>2.1.6.RELEASE</version>
</dependency>
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.9.3</version>
</dependency>

redis配置:

server:
 port: 8000

spring:
 redis:
  host: 23.95.x.x
  port: 6379
  timeout: 20s
  database: 0
  jedis:
   pool:
    max-active: 5
    max-idle: 3
    max-wait: 5s
  password: testtest

配置类:

package me.yanand.config;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisConfig{
 
  private Duration timeOut = Duration.ofMinutes(30);
  @Bean
  public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
        //设置缓存超时时间 30分钟
        .entryTtl(timeOut)
        //设置key序列化方式
        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
        //设置value序列化方式
        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
        .disableCachingNullValues();
    return RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config).transactionAware().build();
  }
}

主要看@EnableCaching注解,这个注解引入了@Import(CachingConfigurationSelector.class),通过CachingConfigurationSelector把代理创建类、CacheInterceptor、CacheOperationSource、BeanFactoryCacheOperationSourceAdvisor注入到容器,spring通过CacheInterceptor拦截器拦截相关带有@Cacheable、@CacheEvict、@CachePut注解的方法并执行相关缓存操作。

CacheInterceptor相关源码:

@Nullable
private Object execute(final CacheOperationInvoker invoker, Method method, CacheOperationContexts contexts) {
 if (contexts.isSynchronized()) {
  CacheOperationContext context = contexts.get(CacheableOperation.class).iterator().next();
  //满足条件执行
  if (isConditionPassing(context, CacheOperationExpressionEvaluator.NO_RESULT)) {
   Object key = generateKey(context, CacheOperationExpressionEvaluator.NO_RESULT);
   Cache cache = context.getCaches().iterator().next();
   try {
     //这里主要看RedisCache的get方法
    return wrapCacheValue(method, cache.get(key, () -> unwrapReturnValue(invokeOperation(invoker))));
   }
   catch (Cache.ValueRetrievalException ex) {
    // The invoker wraps any Throwable in a ThrowableWrapper instance so we
    // can just make sure that one bubbles up the stack.
    throw (CacheOperationInvoker.ThrowableWrapper) ex.getCause();
   }
  }
  else {
   //不满足直接执行相关方法
   return invokeOperation(invoker);
  }
 }
 ...省略
}

RedisCache相关代码:

public synchronized <T> T get(Object key, Callable<T> valueLoader) {
  ValueWrapper result = get(key);
        //缓存中有值则返回
  if (result != null) {
   return (T) result.get();
  }
        //缓存中不存在则执行相关方法
  T value = valueFromLoader(key, valueLoader);
  put(key, value);
  return value;
 }

注解使用:

package me.yanand.dao;
import me.yanand.pojo.User;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class UserDao {
  @Cacheable(cacheNames = "users",key = "#root.targetClass+#name", unless = "#result eq null")
  public User getUser(String name){
    return new User("张三",30);
  }
  @CacheEvict(cacheNames = "users", key = "#root.targetClass+#name")
  public void delUser(String name){
  }
}

测试:

通过postman触发相关方法,现在我们连上redis查看缓存写入情况

这里我们看到key已经写入,过期时间也存在

现在我们删除缓存

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • springboot-启动bean冲突的解决

    springboot-启动bean冲突的解决

    这篇文章主要介绍了springboot-启动bean冲突的解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-03-03
  • Java中CaffeineCache自定义缓存时间的实现

    Java中CaffeineCache自定义缓存时间的实现

    本文主要介绍了Java中CaffeineCache自定义缓存时间的实现,通过声明缓存value值holder对象并创建缓存容器,可以为不同的key值指定不同的过期时间,具有一定的参考价值,感兴趣的可以了解一下
    2025-02-02
  • java实现双色球机选号码生成器

    java实现双色球机选号码生成器

    这篇文章主要为大家详细介绍了java实现双色球机选号码生成器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-01-01
  • Java 图文并茂讲解主方法中的String[] args参数作用

    Java 图文并茂讲解主方法中的String[] args参数作用

    很多老铁不清楚JAVA主方法中main()里面的的参数是什么意思,以及有什么作用,接下来给大家用最通俗易懂的话来讲解,还不清楚的朋友来看看吧
    2022-04-04
  • Postman form-data、x-www-form-urlencoded的区别及说明

    Postman form-data、x-www-form-urlencoded的区别及说明

    这篇文章主要介绍了Postman form-data、x-www-form-urlencoded的区别及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-03-03
  • Spring Boot静态资源路径的配置与修改详解

    Spring Boot静态资源路径的配置与修改详解

    最近在做SpringBoot项目的时候遇到了“白页”问题,通过查资料对SpringBoot访问静态资源做了总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-09-09
  • JDBC中Fetchsize的实现

    JDBC中Fetchsize的实现

    fetchsize是指在执行数据库查询时,每次从数据库中获取的记录条数,它对内存使用和网络传输效率有重要影响,在MyBatis中,可以通过全局设置或语句级别设置fetchsize,来控制查询操作的内存使用和提升性能,合理的fetchsize设置能有效减少网络往返次数和防止内存溢出
    2024-09-09
  • java中把字符串转成 double的方法

    java中把字符串转成 double的方法

    Java 中可以使用 Double 类中的静态方法 parseDouble() 将一个字符串转换为 double 类型的数值,本文结合实例代码对java字符串转成 double详细讲解,需要的朋友参考下吧
    2023-08-08
  • 详谈jvm--Java中init和clinit的区别

    详谈jvm--Java中init和clinit的区别

    下面小编就为大家带来一篇详谈jvm--Java中init和clinit的区别。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • SpringBoot Test类注入失败的解决

    SpringBoot Test类注入失败的解决

    这篇文章主要介绍了SpringBoot Test类注入失败的解决方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-03-03

最新评论