Spring Boot
整合
Ehcache
修改
pom
文件
<!-- Spring Boot 缓存支持启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Ehcache 坐标 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
创建
Ehcache
的配置文件
文件名:ehcache.xml
位置:src/main/resources/ehcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<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
文件
#项目端口配置
server.port=8080
server.address=0.0.0.0
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=UTF8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root
spring.datasouce.type=com.alibaba.druid.pool.DruidDataSource
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.devtools.restart.enabled=true
spring.cache.ehcache.config=classpath:ehcache.xml
修改启动类
package com.bjsxt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching//启用缓存机制
public class BootDataApplication {
public static void main(String[] args) {
SpringApplication.run(BootDataApplication.class, args);
}
}
创建业务层
package com.bjsxt.service.impl;
import com.bjsxt.dao.UserDao;
import com.bjsxt.pojo.Users;
import com.bjsxt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserDao ud;
@Override
@CacheEvict(value = "users",allEntries = true)//清空缓存
public void addUser(Users users) {
ud.save(users);
}
@Override
@Cacheable(value = "users")//配置缓存,查找缓存文件
public List<Users> findall() {
List<Users> usersList = ud.findAll();
return usersList;
}
@Override
@Cacheable(value = "users",key = "#pageable.pageSize")//配置缓存,配置缓存的key
public Page<Users> findUserByPage(Pageable pageable) {
Page<Users> usersPage = ud.findAll(pageable);
return usersPage;
}
}
修改实体类
Users
需要实现序列化接口
package com.bjsxt.pojo;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "users")
@Data
public class Users implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "userid")
private int userid;
@Column(name = "username")
private String username;
@Column(name = "userage")
private int userage;
public Users(){}
public Users(String username, int userage) {
this.username = username;
this.userage = userage;
}
}
测试
package com.bjsxt.test;
import com.bjsxt.BootDataApplication;
import com.bjsxt.dao.UserDao;
import com.bjsxt.pojo.Users;
import com.bjsxt.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = BootDataApplication.class)
public class UserTest {
@Autowired
UserService us;
@Autowired
UserDao ud;
/**
* 添加用户
*/
@Test
public void TestAddUser(){
Users users=new Users();
users.setUsername("杨彪");
users.setUserage(27);
us.addUser(users);
}
@Test
public void findByNameAndAge(){
Specification<Users> spec=new Specification<Users>() {
@Override
public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
/*List<Predicate> predicates=new ArrayList<>();
predicates.add(criteriaBuilder.equal(root.get("username"),"asd"));
predicates.add(criteriaBuilder.equal(root.get("userage"),"123"));
Predicate[] arr=new Predicate[predicates.size()];
return criteriaBuilder.and(predicates.toArray(arr));*/
return criteriaBuilder.or(criteriaBuilder.equal(root.get("username"),"asd"),criteriaBuilder.equal(root.get("userage"),"22"));
}
};
List<Users> users = ud.findAll(spec);
for (Users user : users) {
System.out.println(user);
}
}
/**
* 测试使用缓存查询所有,第二次不会打印sql语句
*/
@Test
public void TestFindAll(){
System.out.println("第一次查询:");
List<Users> users = us.findall();
for (Users user : users) {
System.out.println("First:"+user);
}
Users use=new Users();
use.setUsername("杨彪3");
use.setUserage(22);
us.addUser(use);
System.out.println("\n第二次查询:");
List<Users> u = us.findall();
for (Users user : u) {
System.out.println("Second:"+user);
}
}
@Test
public void findUserByPage(){
Pageable pageable=new PageRequest(0,2);
System.out.println("第一次查询:");
Page<Users> userByPage = us.findUserByPage(pageable);
long totalElements = userByPage.getTotalElements();
System.out.println("First总条数:"+totalElements);
System.out.println("\n第二次查询:");
Page<Users> userByPage2 = us.findUserByPage(pageable);
long totalElements2 = userByPage2.getTotalElements();
System.out.println("Second总条数:"+totalElements2);
System.out.println("\n第三次查询:");
pageable=new PageRequest(1,2);
Page<Users> userByPage3 = us.findUserByPage(pageable);
long totalElements3 = userByPage3.getTotalElements();
System.out.println("Third总条数:"+totalElements3);
}
}