本文介绍下SpringBoot整合SpringDataJPA后加入缓存组件Ehcache的操作。
创建一个SpringBoot项目,添加如下依赖。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.14</version>
</dependency>
<dependency>
<groupId>error</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
</dependencies>
添加Ehcache的配置文件和application.properties
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir"/>
<!--defaultCache:echcache 的默认缓存策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- 自定义缓存策略 -->
<cache name="users"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
application.properties
# mysql 的相关连接信息
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
# 关联Ehcache的配置文件
spring.cache.ehcache.cofnig=ehcache.xml
/**
* @program: springboot-ehcache
* @description: 用户对应的实体类
* @author: 波波烤鸭
* @create: 2019-05-17 11:22
*/
@Entity
@Table(name="users")
public class User implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="userid")
private Integer userid;
@Column(name="username")
private String username;
@Column(name="userage")
private Integer userage;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getUserage() {
return userage;
}
public void setUserage(Integer userage) {
this.userage = userage;
}
@Override
public String toString() {
return "User{" +
"userid=" + userid +
", username='" + username + '\'' +
", userage=" + userage +
'}';
}
}
创建Dao接口并继承JpaRepository
/**
* @program: springboot-ehcache
* @description: 持久层实现Jpa
* @author: 波波烤鸭
* @create: 2019-05-17 11:25
*/
public interface UsersRepository extends JpaRepository<User,Integer> {
}
public interface UserService {
List<User> findUserAll();
User findUserById(Integer id);
Page<User> findUserByPage(Pageable pageable);
void saveUsers(User users);
}
/**
* @program: springboot-ehcache
* @description: 业务层实现类
* @author: 波波烤鸭
* @create: 2019-05-17 11:27
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UsersRepository usersRepository;
@Override
@Cacheable(value="users")
public List<User> findUserAll() {
return this.usersRepository.findAll();
}
@Override
//@Cacheable:对当前查询的对象做缓存处理
@Cacheable(value="users")
public User findUserById(Integer id) {
return this.usersRepository.findById(id).get();
}
@Override
@Cacheable(value="users",key="#pageable.pageSize")
public Page<User> findUserByPage(Pageable pageable) {
return this.usersRepository.findAll(pageable);
}
@Override
//@CacheEvict(value="users",allEntries=true) 清除缓存中以users缓存策略缓存的对象
@CacheEvict(value="users",allEntries=true)
public void saveUsers(User users) {
this.usersRepository.save(users);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringbootEhcacheApplication.class})
public class SpringbootEhcacheApplicationTests {
@Resource
private UserService userService;
@Test
//@Transactional
//@Rollback(false)//取消自动回滚
public void contextLoads() {
//第一次查询
System.out.println(this.userService.findUserById(6));
//第二次查询
System.out.println(this.userService.findUserById(6));
}
@Test
public void testFindUserByPage(){
Pageable pageable = new PageRequest(0, 2);
//第一次查询
System.out.println(this.userService.findUserByPage(pageable).getTotalElements());
//第二次查询
System.out.println(this.userService.findUserByPage(pageable).getTotalElements());
//第三次查询
pageable = new PageRequest(1, 2);
System.out.println(this.userService.findUserByPage(pageable).getTotalElements());
}
@Test
public void testFindAll(){
//第一次查询
System.out.println(this.userService.findUserAll().size());
User users = new User();
users.setUsername("bobo kaoya");
users.setUserage(22);
this.userService.saveUsers(users);
//第二次查询
System.out.println(this.userService.findUserAll().size());
}
}