首页 > 其他分享 >Spring Boot 2.x基础教程:EhCache缓存的使用

Spring Boot 2.x基础教程:EhCache缓存的使用

时间:2022-08-26 11:13:11浏览次数:86  
标签:EhCache 缓存 name Spring Boot User CacheManager

在Spring Boot中通过@EnableCaching注解自动化配置合适的缓存管理器(CacheManager),Spring Boot根据下面的顺序去侦测缓存提供者:

  • Generic
  • JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
  • EhCache 2.x
  • Hazelcast
  • Infinispan
  • Couchbase
  • Redis
  • Caffeine
  • Simple

除了按顺序侦测外,我们也可以通过配置属性spring.cache.type来强制指定。我们也可以通过debug调试查看cacheManager对象的实例来判断当前使用了什么缓存。在上一篇中,我们也展示了如何去查看当前使用情况。

当我们不指定具体其他第三方实现的时候,Spring Boot的Cache模块会使用ConcurrentHashMap来存储。而实际生产使用的时候,因为我们可能需要更多其他特性,往往就会采用其他缓存框架,所以接下来我们会分几篇分别介绍几个常用优秀缓存的整合与使用。

使用EhCache

本篇我们将介绍如何在Spring Boot中使用EhCache进程内缓存。这里我们将沿用上一篇的案例结果来进行改造,以实现EhCache的使用。

先回顾下这个基础案例的三个部分:

User实体的定义

@Entity
@Data
@NoArgsConstructor
public class User {

@Id
@GeneratedValue
private Long id;

private String name;
private Integer age;

public User(String name, Integer age) {
this.name = name;
this.age = age;
}
}

User实体的数据访问实现(涵盖了缓存注解)

@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {

@Cacheable
User findByName(String name);

}

测试验证用例(涵盖了CacheManager的注入,可用来观察使用的缓存管理类)

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter51ApplicationTests {

@Autowired
private UserRepository userRepository;

@Autowired
private CacheManager cacheManager;

@Test
public void test() throws Exception {
// 创建1条记录
userRepository.save(new User("AAA", 10));

User u1 = userRepository.findByName("AAA");
System.out.println("第一次查询:" + u1.getAge());

User u2 = userRepository.findByName("AAA");
System.out.println("第二次查询:" + u2.getAge());
}

}

接下来我们通过下面的几步操作,就可以轻松的把上面的缓存应用改成使用ehcache缓存管理。

第一步:在pom.xml中引入ehcache依赖

<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>

在Spring Boot的parent管理下,不需要指定具体版本,会自动采用Spring Boot中指定的版本号。

第二步:在src/main/resources目录下创建:ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">

<cache name="users"
maxEntriesLocalHeap="200"
timeToLiveSeconds="600">
</cache>

</ehcache>

完成上面的配置之后,再通过debug模式运行单元测试,观察此时CacheManager已经是EhCacheManager实例,说明EhCache开启成功了。或者在测试用例中加一句CacheManager的输出,比如:

@Autowired
private CacheManager cacheManager;

@Test
public void test() throws Exception {
System.out.println("CacheManager type : " + cacheManager.getClass());

userRepository.save(new User("AAA", 10));

User u1 = userRepository.findByName("AAA");
System.out.println("第一次查询:" + u1.getAge());

User u2 = userRepository.findByName("AAA");
System.out.println("第二次查询:" + u2.getAge());
}

执行测试输出可以得到:

CacheManager type : class org.springframework.cache.ehcache.EhCacheCacheManager
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into user (age, name, id) values (?, ?, ?)
2020-07-14 18:09:28.465 INFO 58538 --- [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
第一次查询:10
第二次查询:10

可以看到:

  1. 第一行输出的CacheManager type为org.springframework.cache.ehcache.EhCacheCacheManager,而不是上一篇中的ConcurrentHashMap了。
  2. 第二次查询的时候,没有输出SQL语句,所以是走的缓存获取

标签:EhCache,缓存,name,Spring,Boot,User,CacheManager
From: https://www.cnblogs.com/jieran/p/16626905.html

相关文章

  • Spring+Vue实现token登录
    原文链接前端代码:https://github.com/Snowstorm0/token-login-vue后端代码:https://github.com/Snowstorm0/token-login-spring使用Spring+Vue实现token登录、退出、......
  • Spring Data 测试时的 Repository 提示为空对象
    错误信息如下:java.lang.NullPointerException atcom.usvisatrack.common.data.tests.jpa.UserRepositoryTest.testInsert(UserRepositoryTest.java:57) atjava.base/j......
  • spring源码
    spring框架生态spring包含两个点IOC:控制反转原来创建对象的时候需要我们自己去new但是用spring容器帮我们创建我们需要的时候直......
  • springMVC RequestMapping
    1.可以加在类上用于模块2.可以加在方法上用于路径 packagecom.cj.mvc.controller;importorg.springframework.stereotype.Controller;importorg.springframew......
  • Spring Bean 详解
    SpringBean详解Ioc实例化Bean的三种方式1创建Bean1使用无参构造函数这也是我们常用的一种。在默认情况下,它会通过反射调⽤⽆参构造函数来创建对象。如果类中没有......
  • spring boot中的缓存管理
    springboot默认的缓存管理常用的缓存注解@EnableCaching:在类上使用,表示使用基于注解的方式进行缓存管理@Cacheable:用在类或者方法上。该注解用在方法上时,在方法执行......
  • springboot集成slf4j配置日志
    slf4j简介slf4j是对所有日志框架制定的一种规范、标准、接口,而不是一个框架的具体实现。springboot集成slf4j的简单示例springboot内部已经集成slf4j。@SpringBootAppl......
  • springboot项目的部署
    方式1:打包成jar包pom.xml中指定项目的打包方式<!--可省略--><packaging>jar</packaging>使用maven进行打包将jar包放到任意一个目录下,执行如下命令nohup命......
  • SpringBoot - 文件上传原理
    文件上传原理来个例子客户端<formrole="form"th:action="@{/upload}"method="post"enctype="multipart/form-data"><divclass="form-group"><label......
  • Spring Boot 运行的时候提示日志错误
    提示的错误信息为:Causedby:java.lang.IllegalArgumentException:LoggerFactoryisnotaLogbackLoggerContextbutLogbackisontheclasspath.EitherremoveLog......