您的位置:首页 > 编程语言 > Java开发

Spring Cloud Spring Boot mybatis分布式微服务云架构(三十三)注解配置与EhCache使用(1)

2018-03-07 10:17 1371 查看

快速入门

首先,下载样例工程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函数完成两次查询。
@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依赖,添加如下内容:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>


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

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

}


在数据访问接口中,增加缓存配置注解,如:
@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {

@Cacheable
User findByName(String name);

}


再来执行以下单元测试,可以在控制台中输出了下面的内容:
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语句,也就直接减少了一次数据库的读取操作。
为了可以更好的观察,缓存的存储,我们可以在单元测试中注入cacheManager。
@Autowired
private CacheManager cacheManager;
使用debug模式运行单元测试,观察cacheManager中的缓存集users以及其中的User对象的缓存加深理解。


源码来源
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐