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

现在我们删除缓存

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

(0)

相关推荐

  • Spring Cache手动清理Redis缓存

    这篇文章主要介绍了Spring Cache手动清理Redis缓存,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 注册cacheRedisTemplate 将 cache 的 RedisTemplate 注册为Bean @Bean(name = "cacheRedisTemplate") public RedisTemplate cacheRedisTemplate(@Qualifier("jedisConnectionFac

  • spring整合redis缓存并以注解(@Cacheable、@CachePut、@CacheEvict)形式使用

    maven项目中在pom.xml中依赖2个jar包,其他的spring的jar包省略: <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>org.springfra

  • springboot接入cachecloud redis示例实践

    最近项目中需要接入  Redis CacheCloud,   CacheCloud是一个开源的 Redis 运维监控云平台,功能十分强大,支持Redis 实例自动部署.扩容.碎片管理.统计.监控等功能, 特别是支持单机.sentinel .cluster三种模式的自动部署,搭建redis集群一步到位轻松搞定. java项目中 接入 CacheCloud redis的方式主要有两种. 第一种就是在 CacheCloud 上创建好redis实例后将对应的IP,端口直接配置以配置形式应用到项目中,优点

  • spring boot+spring cache实现两级缓存(redis+caffeine)

    spring boot中集成了spring cache,并有多种缓存方式的实现,如:Redis.Caffeine.JCache.EhCache等等.但如果只用一种缓存,要么会有较大的网络消耗(如Redis),要么就是内存占用太大(如Caffeine这种应用内存缓存).在很多场景下,可以结合起来实现一.二级缓存的方式,能够很大程度提高应用的处理效率. 内容说明: 缓存.两级缓存 spring cache:主要包含spring cache定义的接口方法说明和注解中的属性说明 spring boot

  • 配置Spring4.0注解Cache+Redis缓存的用法

    前言: 目前公司项目在上一个技术架构的处理,已经搭建好了Redis,但redis只用在了做session的管理,然而 后台的对象缓存没有用上 1. redis 和 ehcache的区别: 简单了解了下,个人觉得 从部署上而言,redis更适合分布式部署,ehcache是在每台应用服务器上开辟一块内存做缓存,集群时还得考虑缓存的情况, redis就不需要考虑缓存了.单独部署在一台服务器中(也可以是在某一台应用服务器中) 2. 项目配置(spring mvc+maven+mybaits+redis)

  • SpringBoot中Shiro缓存使用Redis、Ehcache的方法

    SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这shiro基础之上的补充内容 第一种:Redis缓存,将数据存储到redis 并且开启session存入redis中. 引入pom <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifac

  • 浅谈SpringCache与redis集成实现缓存解决方案

    缓存可以说是加速服务响应速度的一种非常有效并且简单的方式.在缓存领域,有很多知名的框架,如EhCache .Guava.HazelCast等.Redis作为key-value型数据库,由于他的这一特性,Redis也成为一种流行的数据缓存工具. 在传统方式下对于缓存的处理代码是非常臃肿的. 例如:我们要把一个查询函数加入缓存功能,大致需要三步. 一.在函数执行前,我们需要先检查缓存中是否存在数据,如果存在则返回缓存数据 二.如果不存在,就需要在数据库的数据查询出来. 三.最后把数据存放在缓存中,当

  • Spring boot redis cache的key的使用方法

    在数据库查询中我们往往会使用增加缓存来提高程序的性能,@Cacheable 可以方便的对数据库查询方法加缓存.本文主要来探究一下缓存使用的key. 搭建项目 数据库 mysql> select * from t_student; +----+--------+-------------+ | id | name | grade_class | +----+--------+-------------+ | 1 | Simone | 3-2 | +----+--------+-----------

  • Spring cache整合redis代码实例

    Spring-Cache是Spring3.1引入的基于注解的缓存技术,本质上它并不是一个具体的缓存实现,而是一个对缓存使用的抽象,通过Spring AOP技术,在原有的代码上添加少量的注解来实现将这个方法转成缓存方法的效果. 本来想来个分析源码,奈何水平有限,先从实战搞起. 先引入依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-start

  • Spring Cache整合Redis实现方法详解

    导入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>

  • Spring Boot整合mybatis(一)实例代码

    sprig-boot是一个微服务架构,加快了spring工程快速开发,以及简便了配置.接下来开始spring-boot与mybatis的整合. 1.创建一个maven工程命名为spring-boot-entity,pom.xml文件配置如下: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:s

  • Spring Boot整合Spring Cache及Redis过程解析

    这篇文章主要介绍了Spring Boot整合Spring Cache及Redis过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.安装redis a.由于官方是没有Windows版的,所以我们需要下载微软开发的redis,网址: https://github.com/MicrosoftArchive/redis/releases b.解压后,在redis根目录打开cmd界面,输入:redis-server.exe redis.wind

  • springboot 整合 freemarker代码实例

    这篇文章主要介绍了springboot 整合 freemarker代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE&l

  • springboot2.1.7整合thymeleaf代码实例

    这篇文章主要介绍了springboot2.1.7整合thymeleaf代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.在pom里面添加thymeleaf依赖 <!--thymeleaf--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymelea

  • SpringBoot2.0整合WebSocket代码实例

    这篇文章主要介绍了SpringBoot2.0整合WebSocket代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 之前公司的某个系统为了实现推送技术,所用的技术都是Ajax轮询,这种方式浏览器需要不断的向服务器发出请求,显然这样会浪费很多的带宽等资源,所以研究了下WebSocket,本文将详细介绍下. 一.什么是WebSocket? WebSocket是HTML5开始提供的一种在单个TCP连接上进行全双工通讯的协议,能更好的节省服务器资

  • springboot整合httpClient代码实例

    这篇文章主要介绍了springboot整合httpClient代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 创建httpClientConfig配置类 @Configuration @PropertySource(value="classpath:/properties/httpClient.properties") public class HttpClientConfig { @Value("${http.ma

  • spring boot整合redis实现RedisTemplate三分钟快速入门

    引入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> RedisTemplate五种数据结构的操作 redisTemplate.opsForValue(); //操作字符串 redisTemplate.opsForHash();

  • Spring Boot整合邮箱发送邮件实例

    目录 1.准备工作 2.代码整合 总结 1. 准备工作 登录进自己的 qq 邮箱获取授权码 设置 – 账户 – POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 点击开始获取授权码,将授权码保存下来,下面代码整合的时候需要使用 2. 代码整合 创建一个 Spring Boot 项目,引入以下依赖 <!-- email --> <dependency> <groupId>org.springframework.boot</groupI

随机推荐