IT必备技能

Spring Boot集成ehcache缓存

2020-01-06  本文已影响0人  问题_解决_分享_讨论_最优

Spring Boot的cache支持多种缓存,参考缓存支持,其中常用的有EhCache和Redis,Redis需要安装redis服务器,而EhCache不依赖任何第三方软件,只需引入jar即可。下面主要介绍ehcache的集成方法。

一、项目准备

直接使用上个章节的源码,Spring Boot集成fastjson

二、添加依赖

在pom.xml里添加ehcache相关的依赖

<!-- cache -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

三、创建ehcache.xml配置文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" dynamicConfig="false">
    <diskStore path="java.io.tmpdir"/>

    <cache name="users" timeToLiveSeconds="300"/>

</ehcache>

cache的属性说明:

四、在application.properties配置文件中指定ehcache配置

添加以下内容:

# ehcache
spring.cache.ehcache.config=classpath:config/ehcache.xml

五、开启缓存支持

在启动类上添加注解@EnableCaching以开启缓存支持。

@EnableCaching
@SpringBootApplication
@MapperScan("com.songguoliang.springboot.mapper")
public class Application{
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

六、代码中使用缓存
Spring提供了4个声明式缓存注解:

捕获.PNG

1、添加缓存

添加缓存只需要在方法上面添加缓存注解即可,我们对com.songguoliang.springboot.service.UserService#selectById方法做如下修改:

/**
 * 使用ehcache.xml配置users缓存,用用户id作为缓存主键
 * @param id
 * @return
 */
@Cacheable(cacheNames = "users",key = "#id")
public User selectById(long id) {
    System.out.println("没有缓存,开始查询数据库……");
    return userMapper.selectByPrimaryKey(id);
}

然后我们启动服务,浏览器输入http://localhost:8080/user/1,可以看到控制台信息显示向数据库查询了数据,如下:

界面结果:

这里写图片描述

再次访问http://localhost:8080/user/1,可以看到控制台并没有信息输出,即并没有向数据库查询数据。

由于我们缓存设置的是300秒,超过这个时间我们再次访问,控制台又可以看到类似上面的信息,说明第一次查询时添加的缓存已经失效并清除,重新添加了缓存。

2、删除缓存
当我们删除用户、修改用户等操作时,需要把缓存也更新。下面例子使用@CacheEvict注解来删除缓存。

UserService里添加以下内容:

@CacheEvict(value = "users",key = "#id")
public void evictUser(Long id) {
    System.out.println("evict user:" + id);
}

UserController里添加一个方法:

@GetMapping("/user/del/{id}")
public String delUser(@PathVariable("id") Long id){
    userService.evictUser(id);
    return "删除成功";
}

重启服务,然后我们先访问http://localhost:8080/user/1添加缓存,之后再访问http://localhost:8080/user/del/1来删除缓存:

这里写图片描述

控制台信息:

这里写图片描述

再次查询用户,又会从数据库查询,说明成功删除了之前的缓存。

打个广告,本人博客地址是:风吟个人博客

上一篇下一篇

猜你喜欢

热点阅读