application.yml:
spring:
cache:
type: encache
业务:
@Service
@Transactional
@CacheConfig(cacheNames = "animal") //配置缓冲空间名
public class AnimalServiceImpl extends AbstractService<Animal> implements AnimalService {
@Override
@Cacheable(key="#p0") //缓存key的默认规则:“缓存空间名:长类名.方法名.入参”|
public Animal getById(Object id) {
return super.getById(id);
}
@Override
@CacheEvict(key="#p0") //删除第一个key为第一个入参的缓存
public int deleteById(Object id) {
return super.deleteById(id);
}
@Override
@CachePut(key="#p0.aid") //如果返回值不为空,则更新入参对象对于aid的缓冲值
public Animal updateAndRtn(Animal animal) {
if (super.update(animal)==1){
return super.getById(animal.getAid());
}
return null;
}
@Override
@CacheEvict(allEntries = true)// 清空缓存
public void clearCache() {
}
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
resources下面要加ehcache.xml:
<?xml version="1.0" encoding="utf-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd">
<cache name="animal"
maxEntriesLocalHeap="200"
timeToLiveSeconds="600">
</cache>
<cache name="action"
maxEntriesLocalHeap="200"
timeToLiveSeconds="600">
</cache>
</ehcache>
启动类要加注解:
@SpringBootApplication
@EnableCaching
public class Dur5Course2SpringmybatistApplication {
public static void main(String[] args) {
SpringApplication.run(Dur5Course2SpringmybatistApplication.class, args);
}
}
测试:
@Autowired
private AnimalService animalService;
@Test
void contextLoads() {
System.out.println(animalService.findAll());
System.out.println(animalService.findAll());
}
@Test
public void testDelete(){
System.out.println(animalService.deleteById(1));
}
@Test
public void testCache(){
System.out.println(animalService.getById(62));
//System.out.println(animalService.deleteById(61));
System.out.println(animalService.getById(62));
}
@Test
public void testChacheUpdate(){
Animal animal=animalService.getById(62);
System.out.println("修改前:"+animal);
animal.setAname("新动物");
animal.setAge(100);
System.out.println("修改后:"+animalService.updateAndRtn(animal));
animalService.clearCache();//清空缓存
System.out.println("修改后的查询:"+animalService.getById(62));
}