1.pom中插入依赖:
<!--guava缓存cache--> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>23.5-jre</version> </dependency>
2.在com.example.mapper.mybatisMap建立一个包cache,在cache下建立一个类LocalCache:
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.util.concurrent.TimeUnit;
public class LocalCache { private static Cache<String, Integer> cache = CacheBuilder.newBuilder() .expireAfterWrite(10L, TimeUnit.MINUTES) //写入10分钟后过期 .maximumSize(50000L) .build(); public Integer getCache(String key){ return (Integer)cache.getIfPresent(key); } public Cache<String, Integer> getCache(){ return cache; } public void setCache(String key, Integer obj){ cache.put(key, obj); } public void removeCache(String key){ cache.invalidate(key); } public void removeAll(){ cache.invalidateAll(); } public long getSize(){ return cache.size(); } }