Spring Boot中的缓存支持(一)注解配置与EhCache使用

本文介绍了如何在Spring Boot中使用注解配置和EhCache实现缓存功能。通过开启缓存,避免了多次数据库查询,提高了应用程序性能。详细讲解了`@CacheConfig`和`@Cacheable`注解的使用,并提供了单元测试案例展示缓存效果。
摘要由CSDN通过智能技术生成
  • application.properties文件中新增spring.jpa.properties.hibernate.show_sql=true,开启hibernate对sql语句的打印

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

@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());

}

}

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

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依赖,添加如下内容:

org.springframework.boot

spring-boot-starter-cache

  • 在Spring Boot
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值