Spring cache整合redis代码实例

所属分类: 软件编程 / java 阅读数: 676
收藏 0 赞 0 分享

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已经写入,过期时间也存在

现在我们删除缓存

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

更多精彩内容其他人还在看

Java遍历Map键、值和获取Map大小的方法示例

本篇文章主要介绍了Java遍历Map键、值和获取Map大小的方法示例,详细的介绍了Java遍历Map的两种实现方法和大小,具有一定的参考价值,有兴趣的可以了解一下。
收藏 0 赞 0 分享

jdk7 中HashMap的知识点总结

HashMap的原理是老生常谈了,不作仔细解说。一句话概括为HashMap是一个散列表,它存储的内容是键值对(key-value)映射。这篇文章主要总结了关于jdk7 中HashMap的知识点,需要的朋友可以参考借鉴,一起来看看吧。
收藏 0 赞 0 分享

spring mvc4的日期/数字格式化、枚举转换示例

本篇文章主要介绍了spring mvc4的日期/数字格式化、枚举转换示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
收藏 0 赞 0 分享

在Java8与Java7中HashMap源码实现的对比

这篇文章主要介绍了在Java8与Java7中HashMap源码实现的对比,内容包括HashMap 的原理简单介绍、结合源码在Java7中是如何解决hash冲突的以及优缺点,结合源码以及在Java8中如何解决hash冲突,balance tree相关源码介绍,需要的朋友可以参考借鉴
收藏 0 赞 0 分享

详解java WebSocket的实现以及Spring WebSocket

这篇文章主要介绍了详解java WebSocket的实现以及Spring WebSocket ,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
收藏 0 赞 0 分享

java 数据结构之删除链表中的元素实例代码

这篇文章主要介绍了java 数据结构之删除链表中的元素实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

spring 定时任务@Scheduled详解

这篇文章主要介绍了spring 定时任务@Scheduled的相关资料,文中通过示例代码介绍的很详细,相信对大家的理解和学习具有一定的参考借鉴价值,有需要的朋友们下面来一起看看吧。
收藏 0 赞 0 分享

MyBatis配置文件的写法和简单使用

MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的持久层框架。这篇文章主要介绍了MyBatis配置文件的写法和简单使用,需要的朋友参考下
收藏 0 赞 0 分享

java 可重启线程及线程池类的设计(详解)

下面小编就为大家带来一篇java 可重启线程及线程池类的设计(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

浅谈java常用的几种线程池比较

下面小编就为大家带来一篇浅谈java常用的几种线程池比较。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多