java-caffeine缓存

引依赖



com.github.ben-manes.caffeine
caffeine



org.springframework
spring-context-support

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> 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> 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 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 list = testCache.getIfPresent("test");
        log.info("缓存取出!!");
        return list;
    }


}

结果:

java-caffeine缓存_第1张图片
java-caffeine缓存_第2张图片

你可能感兴趣的:(java,缓存,spring)