添加maven依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
入口类开启缓存支持:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication//核心注解,主要是开启自动配置
//@EntityScan(basePackages = "com.example.**")
//开启缓存支持
@EnableCaching
public class DemoApplication {
//项目启动的入口
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
service接口:
package com.example.demo.part3.chapter8.cache;
import com.example.demo.part3.chapter8.jpa.Boy;
public interface CacheService {
public Boy save(Boy boy);
public void remove(int id);
public Boy findOne(int id);
}
实现接口:
package com.example.demo.part3.chapter8.cache;
import com.example.demo.part3.chapter8.jpa.Boy;
import com.example.demo.part3.chapter8.jpa.BoyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class CacheServiceImpl implements CacheService{
@Autowired
BoyRepository boyRepository;
@Override
//cacheput缓存新增的或者更新的数据到缓存,其中缓存名称为boy
//数据的key是boy 的id
@CachePut(value = "boy",key = "#boy.id")
public Boy save(Boy boy) {
System.out.println("增加了id为"+boy.getId()+"的缓存");
return boyRepository.save(boy);
}
@Override
//从缓存boy中删除key为id的数据
@CacheEvict(value = "boy")
public void remove(int id) {
System.out.println("删除了id为"+id+"的缓存");
//boyRepository.delete(id);
}
@Override
//缓存key为id的数据到缓存boy中
@Cacheable(value = "boy",key = "#id")
public Boy findOne(int id) {
System.out.println("增加了id为"+id+"的缓存");
Boy boy=boyRepository.findOne(id);
return boy;
}
}
控制层:
package com.example.demo.part3.chapter8.cache;
import com.example.demo.part3.chapter8.jpa.Boy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/cc2")
public class CacheController2 {
@Autowired
CacheService cacheService;
@RequestMapping("/save")
public Boy save(Boy boy){
return cacheService.save(boy);
}
@RequestMapping("/remove")
public void remove(int id){
cacheService.remove(id);
}
@RequestMapping("/findOne")
public Boy findOne(int id){
return cacheService.findOne(id);
}
}
1. 执行findOne,再次执行findOne
第二次,控制台没有输出,表明没有操作数据库
2.执行save,再执行findOne
第二次,控制台没有输出,表明没有操作数据库
3.执行findOne,执行remove,再执行findOne