Guava Cache本地缓存在 Spring Boot应用中的实践

ZenBook S13 97%屏占比


概述

在如今高并发的互联网应用中,缓存的地位举足轻重,对提升程序性能帮助不小。而 3.x开始的 Spring也引入了对 Cache的支持,那对于如今发展得如火如荼的 Spring Boot来说自然也是支持缓存特性的。当然 Spring Boot默认使用的是 SimpleCacheConfiguration,即使用 ConcurrentMapCacheManager 来实现的缓存。但本文将讲述如何将 Guava Cache缓存应用到 Spring Boot应用中。

Guava Cache是一个全内存的本地缓存实现,而且提供了线程安全机制,所以特别适合于代码中已经预料到某些值会被多次调用的场景

下文就上手来摸一摸它,结合对数据库的操作,我们让 Guava Cache作为本地缓存来看一下效果!

注: 本文首发于 My Personal Blog:CodeSheep·程序羊,欢迎光临 小站


准备工作

  • 准备好数据库和数据表并插入相应实验数据(MySQL)

比如我这里准备了一张用户表,包含几条记录:

准备好MySQL数据库和数据表

我们将通过模拟数据库的存取操作来看看 Guava Cache缓存加入后的效果。


搭建工程:Springboot + MyBatis + MySQL + Guava Cache

pom.xml 中添加如下依赖:

1 <dependencies> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-web</artifactId> 5 </dependency> 6 7 <dependency> 8 <groupId>org.springframework.boot</groupId> 9 <artifactId>spring-boot-starter-test</artifactId> 10 <scope>test</scope> 11 </dependency> 12 13 <!--for mybatis--> 14 <dependency> 15 <groupId>org.mybatis.spring.boot</groupId> 16 <artifactId>mybatis-spring-boot-starter</artifactId> 17 <version>1.3.2</version> 18 </dependency> 19 20 <!--for Mysql--> 21 <dependency> 22 <groupId>mysql</groupId> 23 <artifactId>mysql-connector-java</artifactId> 24 <scope>runtime</scope> 25 </dependency> 26 27 <!-- Spring boot Cache--> 28 <dependency> 29 <groupId>org.springframework.boot</groupId> 30 <artifactId>spring-boot-starter-cache</artifactId> 31 </dependency> 32 33 <!--for guava cache--> 34 <dependency> 35 <groupId>com.google.guava</groupId> 36 <artifactId>guava</artifactId> 37 <version>27.0.1-jre</version> 38 </dependency> 39 40 </dependencies>

建立 Guava Cache配置类

引入 Guava Cache的配置文件 GuavaCacheConfig

1@Configuration 2@EnableCaching 3public class GuavaCacheConfig { 4 5 @Bean 6 public CacheManager cacheManager() { 7 GuavaCacheManager cacheManager = new GuavaCacheManager(); 8 cacheManager.setCacheBuilder( 9 CacheBuilder.newBuilder(). 10 expireAfterWrite(10, TimeUnit.SECONDS). 11 maximumSize(1000)); 12 return cacheManager; 13 } 14}

Guava Cache配置十分简洁,比如上面的代码配置缓存存活时间为 10 秒,缓存最大数目为 1000 个


配置 application.properties

1server.port=82 2 3# Mysql 数据源配置 4spring.datasource.url=jdbc:mysql://121.116.23.145:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false 5spring.datasource.username=root 6spring.datasource.password=xxxxxx 7spring.datasource.driver-class-name=com.mysql.jdbc.Driver 8 9# mybatis配置 10mybatis.type-aliases-package=cn.codesheep.springbt_guava_cache.entity 11mybatis.mapper-locations=classpath:mapper/*.xml 12mybatis.configuration.map-underscore-to-camel-case=true

编写数据库操作和 Guava Cache缓存的业务代码

  • 编写 entity

    public class User {

    1private Long userId; 2private String userName; 3private Integer userAge; 4 5public Long getUserId() { 6 return userId; 7} 8 9public void setUserId(Long userId) { 10 this.userId = userId; 11} 12 13public String getUserName() { 14 return userName; 15} 16 17public void setUserName(String userName) { 18 this.userName = userName; 19} 20 21public Integer getUserAge() { 22 return userAge; 23} 24 25public void setUserAge(Integer userAge) { 26 this.userAge = userAge; 27}

    }

  • 编写 mapper

    public interface UserMapper {

    1List<User> getUsers(); 2int addUser(User user); 3List<User> getUsersByName( String userName );

    }

  • 编写 service

    @Service public class UserService {

    1@Autowired 2private UserMapper userMapper; 3 4public List<User> getUsers() { 5 return userMapper.getUsers(); 6} 7 8public int addUser( User user ) { 9 return userMapper.addUser(user); 10} 11 12@Cacheable(value = "user", key = "#userName") 13public List<User> getUsersByName( String userName ) { 14 List<User> users = userMapper.getUsersByName( userName ); 15 System.out.println( "从数据库读取,而非读取缓存!" ); 16 return users; 17}

    }

看得很明白了,我们在 getUsersByName接口上添加了注解:@Cacheable。这是 缓存的使用注解之一,除此之外常用的还有 @CachePut@CacheEvit,分别简单介绍一下:

  1. @Cacheable:配置在 getUsersByName方法上表示其返回值将被加入缓存。同时在查询时,会先从缓存中获取,若不存在才再发起对数据库的访问
  2. @CachePut:配置于方法上时,能够根据参数定义条件来进行缓存,其与 @Cacheable不同的是使用 @CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中,所以主要用于数据新增和修改操作上
  3. @CacheEvict:配置于方法上时,表示从缓存中移除相应数据。
  • 编写 controller

    @RestController public class UserController {

    1@Autowired 2private UserService userService; 3 4@Autowired 5CacheManager cacheManager; 6 7@RequestMapping( value = "/getusersbyname", method = RequestMethod.POST) 8public List<User> geUsersByName( @RequestBody User user ) { 9 System.out.println( "-------------------------------------------" ); 10 System.out.println("call /getusersbyname"); 11 System.out.println(cacheManager.toString()); 12 List<User> users = userService.getUsersByName( user.getUserName() ); 13 return users; 14}

    }


改造 Spring Boot应用主类

主要是在启动类上通过 @EnableCaching注解来显式地开启缓存功能

1@SpringBootApplication 2@MapperScan("cn.codesheep.springbt_guava_cache") 3@EnableCaching 4public class SpringbtGuavaCacheApplication { 5 public static void main(String[] args) { 6 SpringApplication.run(SpringbtGuavaCacheApplication.class, args); 7 } 8}

最终完工的整个工程的结构如下:

完整工程结构


实际实验

通过多次向接口 localhost:82/getusersbyname POST数据来观察效果:

向接口提交数据

可以看到缓存的启用和失效时的效果如下所示(上文 Guava Cache的配置文件中设置了缓存 user的实效时间为 10s):

缓存的启用和失效时的取数据效果

怎么样,缓存的作用还是很明显的吧!


后 记

由于能力有限,若有错误或者不当之处,还请大家批评指正,一起学习交流!



点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

RPC框架实践之:Google gRPC

!MyDesktop(https://uploadimages.jianshu.io/upload_images/982424787bc1d746154471c.jpeg?imageMogr2/autoorient/strip%7CimageView2/2/w/1240)MyDesktop概述gRP

SpringBoot热部署加持

!Ultrafine5K(https://uploadimages.jianshu.io/upload_images/98242478bcc770c7a2f4a1f.png?imageMogr2/autoorient/strip%7CimageView2/2/w/1240)概述进行SpringBoot的Web开发过程中

Docker容器跨主机通信之:直接路由方式

!Desktop(https://uploadimages.jianshu.io/upload_images/9824247a72fa1bbdcf60e4e.jpeg?imageMogr2/autoorient/strip%7CimageView2/2/w/1240)概述就目前Docker自身默认的网络来说