引依赖
<!-- caffeine缓存依赖-->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
cache工具类,写出一个一个自己需要使用的caffeine实例
/**
* Caffeine缓存
*
* Author: Simon Wayne
* @ClassName CacheConfig
* @Date: 2023/1/31 19:19
* @version: 1.0
*/
@Configuration
public class CaffeineConfig {
@Bean(value = "testCache")
public Cache<String, List<Student>> testCache(){
return Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.build();
}
}
controller
/**
* Author: Simon Wayne
*
* @Date: 2023/1/31 19:21
* @version: 1.0
*/
@RequestMapping("/cache")
@RestController
@Slf4j
public class CacheController {
@Autowired
private Cache<String, List<Student>> testCache;
@RequestMapping("/3")
public String test3(){
// 存入缓存
Student student0 = new Student().builder().age(21).name("simon0").height(185).sex("boy").selfAssessment("cool").build();
Student student1 = new Student().builder().age(22).name("simon1").height(185).sex("boy").selfAssessment("cool").build();
Student student2 = new Student().builder().age(23).name("simon2").height(185).sex("boy").selfAssessment("cool").build();
Student student3 = new Student().builder().age(24).name("simon3").height(185).sex("boy").selfAssessment("cool").build();
ArrayList<Student> students = new ArrayList<>();
students.add(student0);
students.add(student1);
students.add(student2);
students.add(student3);
testCache.put("test",students);
return "存入学生信息!";
}
@RequestMapping("/4")
public Object test4(){
List<Student> list = testCache.getIfPresent("test");
log.info("缓存取出!!");
return list;
}
}
结果: