spring 集成 google 一级缓存实战使用
1、pom文件jar引入
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
2、实例化对象
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.tuling.tulingmall.domain.PmsProductParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;
@Slf4j
@Component
public class LocalCache<T> {
private Cache<String,T> localCache = null;
@PostConstruct
private void init(){
localCache = CacheBuilder.newBuilder()
//设置本地缓存容器的初始容量
.initialCapacity(10)
//设置本地缓存的最大容量
.maximumSize(500)
//设置写缓存后多少秒过期
.expireAfterWrite(60, TimeUnit.SECONDS).build();
}
public void setLocalCache(String key,T object){
localCache.put(key,object);
}
/***
* 返回值 如果不存在返回null
* @param key
* @param <T>
* @return
*/
public <T> T getCache(String key){
return (T) localCache.getIfPresent(key);
}
public void remove(String key){
localCache.invalidate(key);
}
}
3、测试伪代码
@Autowired
private LocalCache<Boolean> cache;
//方法中的伪代码
cache.remove(RedisKeyPrefixConst.MIAOSHA_STOCK_CACHE_PREFIX + productId);
Boolean localcache = cache.getCache(RedisKeyPrefixConst.MIAOSHA_STOCK_CACHE_PREFIX + productId);
cache.setLocalCache(RedisKeyPrefixConst.MIAOSHA_STOCK_CACHE_PREFIX + productId,true);
4、总结、一级缓存即JVM缓存有多种多样的实现方式、比如map就行,要结合业务场景选择最合适的才是最好的。
也可参考:其他配置方式
到此、spring 集成 google 一级缓存实战使用分享完毕,大家多测试多验证,定会很快掌握。