Spring Boot 2.X整合Spring-cache(让你的网站速度飞起来)

计算机领域有人说过一句名言:“计算机科学领域的任何问题都可以通过增加一个中间层来解决”,今天我们就用Spring-cache给网站添加一层缓存,让你的网站速度飞起来。

本文目录

一、Spring Cache介绍二、缓存注解介绍三、Spring Boot+Cache实战1、pom.xml引入jar包2、启动类添加@EnableCaching注解3、配置数据库和redis连接4、配置CacheManager5、使用缓存注解6、查看缓存效果7、注意事项

一、Spring Cache介绍

Spring 3.1引入了基于注解的缓存(cache)技术,它本质上是一个对缓存使用的抽象,通过在既有代码中添加少量它定义的各种注解,就能够达到缓存方法的效果。

Spring Cache接口为缓存的组件规范定义,包含缓存的各种操作集合,并提供了各种xxxCache的实现,如RedisCache,EhCacheCache,ConcurrentMapCache等;

项目整合Spring Cache后每次调用需要缓存功能的方法时,Spring会检查检查指定参数的指定的目标方法是否已经被调用过,如果有就直接从缓存中获取结果,没有就调用方法并把结果放到缓存。

二、缓存注解介绍

对于缓存声明,Spring的缓存提供了一组java注解:

@CacheConfig:设置类级别上共享的一些常见缓存设置。

  • @Cacheable:触发缓存写入。
  • @CacheEvict:触发缓存清除。
  • @Caching 将多种缓存操作分组
  • @CachePut:更新缓存(不会影响到方法的运行)。

@CacheConfig

@CacheConfig(cacheNames = "user")
@Service
public class UserServiceImpl implements UserService {}

@Cacheable

  • 如果key不存在,查询db,并将结果更新到缓存中。
  • 如果key存在,直接查询缓存中的数据。
  //查询数据库后 数据添加到缓存
  @Override
  @Cacheable(cacheNames = "cacheManager", key = "'USER:'+#id", unless = "#result == null")
  public User getUser(Integer id) {
    return repository.getUser(id);
  }

@CachePut

  //修改数据后更新缓存
  @Override
  @CachePut(cacheNames = "cacheManager", key = "'USER:'+#updateUser.id", unless = "#result == null")
  public User updateUser(User updateUser) {
    return repository.save(updateUser);
  }

@CacheEvict

  //清除一条缓存,key为要清空的数据
  @Override
  @CacheEvict(cacheNames = "cacheManager", key = "'USER:'+#id")
  public void deleteUser(Integer id) {
    repository.deleteById(id);
  }

三、Spring Boot+Cache实战

1、pom.xml引入jar包

<!-- 引入缓存 starter -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- 引入 redis -->
<dependency>
  <groupId&>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2、启动类添加@EnableCaching注解

@EnableCaching注解是spring framework中的注解驱动的缓存管理功能,当你在配置类(@Configuration)上使用@EnableCaching注解时,会触发一个post processor,这会扫描每一个spring bean,查看是否已经存在注解对应的缓存。如果找到了,就会自动创建一个代理拦截方法调用,使用缓存的bean执行处理。

启动类部分代码如下:

3、配置数据库和redis连接

application.properties部分配置如下:

#配置数据源信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.1.1:3306/test
spring.datasource.username=root
spring.datasource.password=1234
#配置jpa
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jackson.serialization.indent_output=true
# Redis服务器地址
spring.redis.host=192.168.1.1
# database
spring.redis.database = 1
# Redis服务器连接端口 使用默认端口6379可以省略配置
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=1234
# 连接池最大连接数(如果配置<=0,则没有限制 )
spring.redis.jedis.pool.max-active=8

4、配置CacheManager

WebConfig.java部分配置如下:

@Bean
  public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
    //缓存配置对象
    RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();

    redisCacheConfiguration = redisCacheConfiguration.entryTtl(Duration.ofMinutes(30L)) //设置缓存的默认超时时间:30分钟
        .disableCachingNullValues()       //如果是空值,不缓存
        .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))     //设置key序列化器
        .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((valueSerializer()))); //设置value序列化器

    return RedisCacheManager
        .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
        .cacheDefaults(redisCacheConfiguration).build();
  }

5、使用缓存注解

UserServiceImpl.java中使用缓存注解示例如下:

//查询数据库后 数据添加到缓存
  @Override
  @Cacheable(cacheNames = "cacheManager", key = "'USER:'+#id", unless = "#result == null")
  public User getUser(Integer id) {
    return repository.getUser(id);
  }

  //清除一条缓存,key为要清空的数据
  @Override
  @CacheEvict(cacheNames = "cacheManager", key = "'USER:'+#id")
  public void deleteUser(Integer id) {
    repository.deleteById(id);
  }

  //修改数据后更新缓存
  @Override
  @CachePut(cacheNames = "cacheManager", key = "'USER:'+#updateUser.id", unless = "#result == null")
  public User updateUser(User updateUser) {
    return repository.save(updateUser);
  }

6、查看缓存效果

启动服务后,访问两次http://localhost:8090/getUser/2接口,从打印日志可以看到,第一次请求打印了sql说明查询了数据库,耗时960,而第二次直接查询的缓存耗时66,增加缓存后速度提升非常明显。

postman访问截图

日志截图

7、注意事项

Spring cache是基于Spring Aop来动态代理机制来对方法的调用进行切面,这里关键点是对象的引用问题,如果对象的方法是内部调用(即 this 引用)而不是外部引用,则会导致 proxy 失效,那么我们的切面就失效,也就是说上面定义的各种注释包括 @Cacheable、@CachePut 和 @CacheEvict 都会失效。

到此Spring Boot 2.X中整合Spring-cache与Redis功能全部实现,有问题欢迎留言沟通哦!

https://github.com/suisui2019/springboot-study

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

(0)

相关推荐

  • springboot集成spring cache缓存示例代码

    本文介绍如何在springboot中使用默认的spring cache, 声明式缓存 Spring 定义 CacheManager 和 Cache 接口用来统一不同的缓存技术.例如 JCache. EhCache. Hazelcast. Guava. Redis 等.在使用 Spring 集成 Cache 的时候,我们需要注册实现的 CacheManager 的 Bean. Spring Boot 为我们自动配置了 JcacheCacheConfiguration. EhCacheCacheCo

  • 使用ehcache三步搞定springboot缓存的方法示例

    本次内容主要介绍基于Ehcache 3.0来快速实现Spring Boot应用程序的数据缓存功能.在Spring Boot应用程序中,我们可以通过Spring Caching来快速搞定数据缓存.接下来我们将介绍如何在三步之内搞定Spring Boot缓存. 1. 创建一个Spring Boot工程并添加Maven依赖 你所创建的Spring Boot应用程序的maven依赖文件至少应该是下面的样子: <?xml version="1.0" encoding="UTF-8

  • springboot+EHcache 实现文章浏览量的缓存和超时更新

    问题描述 当我们需要统计文章的浏览量的时候,最常规的做法就是: 1.访问文章链接www.abc.com/article/{id} 2.在控制层获取Article实体 3.得到文章浏览量count并且count++ 4.最后update实体Article. 这么做对没有访问量的网站来说很棒,如果网站访问量很大,这么不停的读写数据库,会对服务器造成很大的压力. 解决思路 引入Ehcache,将文章的访问量存在cache中,每点击一次文章,将cache中的count加1.在有效的时间内访问文章只是将c

  • SpringBoot手动使用EhCache的方法示例

    SpringBoot在annotation的层面实现了数据缓存的功能,基于Spring的AOP技术.所有的缓存配置只是在annotation层面配置,像声明式事务一样. Spring定义了CacheManager和Cache接口统一不同的缓存技术.其中CacheManager是Spring提供的各种缓存技术的抽象接口.而Cache接口包含缓存的各种操作. CacheManger 针对不同的缓存技术,需要实现不同的cacheManager,Spring定义了如下的cacheManger实现. Ca

  • 详解springboot整合ehcache实现缓存机制

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心容量问题. spring-boot是一个快速的集成框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 由于spring-boot无需任何样板化的配置文件,所以spring-boot集成一些其他框架时会有略微的

  • 详解SpringBoot缓存的实例代码(EhCache 2.x 篇)

    本篇介绍了SpringBoot 缓存(EhCache 2.x 篇),分享给大家,具体如下: SpringBoot 缓存 在 spring Boot中,通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者: Generic JCache (JSR-107) EhCache 2.x Hazelcast Infinispan Redis Guava Simple 关于 Spring Boot 的缓存机制: 高速

  • springboot整合EHCache的实践方案

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心容量问题. spring-boot是一个快速的集成框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 用户登录之后,几乎之后展示任何页面都需要显示一下用户信息.可以在用户登录成功之后将用户信息进行缓存,之后直

  • springboot使用GuavaCache做简单缓存处理的方法

    问题背景 实际项目碰到一个上游服务商接口有10秒的查询限制(同个账号). 项目中有一个需求是要实时统计一些数据,一个应用下可能有多个相同的账号.由于服务商接口的限制,当批量查询时,可能出现同一个账号第一次查询有数据,但第二次查询无数据的情况. 解决方案 基于以上问题,提出用缓存的过期时间来解决. 这时,可用Redis和Guava Cache来解决: 当批量查询时,同一个账号第一次查询有数据则缓存并设置过期时间10s, 后续查询时直接从缓存中取,没有再从服务商查询. 最终采用Guava Cache

  • springboot整合ehcache 实现支付超时限制的方法

    下面给大家介绍springboot整合ehcache 实现支付超时限制的方法,具体内容如下所示: <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.11</version> </dependency> pom文件中引入ehcache依赖 在类路径下存放ehcache.

  • SpringBoot 集成 Memcached的方法示例

    Memcached 介绍 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度.Memcached基于一个存储键/值对的hashmap.其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信. 因为 Spring Boot 没有针对 Memcached 提供对应的组建包,因此需要我们自己来集成.官方推出的 Ja

随机推荐