Spring Boot中的缓存支持

20190929156972721778897.png

Java缓存浅析

随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决这一问题非常好的手段之一。Spring 3开始提供了强大的基于注解的缓存支持,可以通过注解配置方式低侵入的给原有Spring应用增加缓存功能,提高数据访问性能。

在Spring Boot中对于缓存的支持,提供了一系列的自动化配置,使我们可以非常方便的使用缓存。下面我们通过一个简单的例子来展示,我们是如何给一个既有应用增加缓存功能的。

快速入门

首先,下载样例工程chapter3-2-2。本例通过spring-data-jpa实现了对User用户表的一些操作,若没有这个基础,可以先阅读《使用Spring-data-jpa简化数据访问层》一文对数据访问有所基础。

准备工作

为了更好的理解缓存,我们先对该工程做一些简单的改造。

application.properties文件中新增spring.jpa.properties.hibernate.show_sql=true,开启hibernate对sql语句的打印

修改单元测试ApplicationTests,初始化插入User表一条用户名为AAA,年龄为10的数据。并通过findByName函数完成两次查询。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {

@Autowired
private UserRepository userRepository;

@Before
public void before() {
userRepository.save(new User("AAA", 10));
}

@Test
public void test() throws Exception {
User u1 = userRepository.findByName("AAA");
System.out.println("第一次查询:" + u1.getAge());

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

}

执行单元测试,我们可以在控制台中看到下面内容。

1
2
3
4
5
Hibernate: insert into user (age, name) values (?, ?)
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
第一次查询:10
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
第二次查询:10

在测试用例执行前,插入了一条User记录。然后每次findByName调用时,都执行了一句select语句来查询用户名为AAA的记录。

引入缓存

在pom.xml中引入cache依赖,添加如下内容:

1
2
3
4
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-cacheartifactId>
dependency>

在Spring Boot主类中增加@EnableCaching注解开启缓存功能,如下:

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableCaching
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

在数据访问接口中,增加缓存配置注解,如:

1
2
3
4
5
6
7
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {

@Cacheable
User findByName(String name);

}

再来执行以下单元测试,可以在控制台中输出了下面的内容:

1
2
3
4
Hibernate: insert into user (age, name) values (?, ?)
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

到这里,我们可以看到,在调用第二次findByName函数时,没有再执行select语句,也就直接减少了一次数据库的读取操作。

原文ehcache的使用

end 😄

0%