1、引入對應(yīng)的依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
2、添加緩存相關(guān)的常量(緩存名稱、緩存過期時(shí)間、緩存大?。?/p>
package com.example.mybatis.demos.web.common;
/**
* 常量定義
*/
public class Constants {
public static class LocalCache {
public static final String CacheName = "my_local_cache_name";
public static final int TTL = 10; // 緩存過期時(shí)間
public static final int CAPACITY = 5000; // 緩存容量
}
}
3、定義枚舉,多個(gè)緩存的話直接遍歷枚舉
package com.example.mybatis.demos.web.enums;
import com.example.mybatis.demos.web.common.Constants;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public enum CacheEnum {
LOCALCACHE(Constants.LocalCache.CacheName,Constants.LocalCache.TTL,Constants.LocalCache.CAPACITY);
private String name;
private int ttl;
private int capacity;
}
4、使用
@Cacheable(cacheNames = Constants.LocalCache.CacheName,key = "#id")
@Override
public Student getStudentByID(int id) {
log.info("get info by id not from local cache={}",id);
return studentMapper.getStudentByID(id);
}