JAVA全系列 教程
3762个小节阅读:7095k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
Cache是Guava提供的一个缓存工具类,它可以帮助我们在内存中缓存数据,提高程序的性能。
Cache的主要方法:
- get(K key, Callable<? extends V> valueLoader):获取指定key的缓存值,如果缓存中没有,则调用valueLoader加载数据并存入缓存。
- getIfPresent(Object key):获取指定key的缓存值,如果缓存中没有,则返回null。
- getAllPresent(Iterable<?> keys):获取指定keys的缓存值,如果缓存中没有,则返回null。
- put(K key, V value):将指定key的缓存值存入缓存。
- putAll(Map<? extends K, ? extends V> m):将指定Map的缓存值存入缓存。
- invalidate(Object key):将指定key的缓存值从缓存中删除。
- invalidateAll(Iterable<?> keys):将指定keys的缓存值从缓存中删除。
- invalidateAll():将所有缓存值从缓存中删除。
- size():获取缓存中缓存值的数量。
- asMap():将缓存转换成Map。
代码示例
xxxxxxxxxx
package com.itbaizhan.springdataredisdemo.service.impl;
import com.google.common.cache.*;
import com.itbaizhan.springdataredisdemo.entity.User;
import com.itbaizhan.springdataredisdemo.mapper.UserMapper;
import com.itbaizhan.springdataredisdemo.service.IUserService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper userMapper;
@Autowired
private RedisTemplate<String,Object> template;
/**
* 本地缓存
*/
private LoadingCache<String, User> localCache = CacheBuilder.newBuilder()
//设置并发级别为16,并发级别是指可以同时写缓存的线程数
.concurrencyLevel(16)
//设置缓存容器的初始容量为1000
.initialCapacity(1000)
//设置缓存最大容量为10000,超过10000之后就会按照LRU最近虽少使用算法来移除缓存项
.maximumSize(10000)
//设缓存1小时没被使用就过期
.expireAfterAccess(1, TimeUnit.HOURS)
//设置要统计缓存的命中率
.recordStats()
//设置缓存的移除通知
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object> notification) {
System.out.println(notification.getKey() + " 被移除了,原因: " + notification.getCause());
}
})
.build(new CacheLoader<String, User>() {
@Override
public User load(String key) throws Exception {
// 1、判断用户id等于1 有没有缓存 user:1
User user = (User) template.opsForValue().get("user:" + key);
if (user != null){
return user;
}
// 2、查询数据库
User users = userMapper.selectById(key);
// 4、加入redis分布式缓存
template.opsForValue().set("user:" + key,users);
return users;
}
});
/**
*
* 根据用户id查询用户
* @param id
* @return
*/
@SneakyThrows
@Override
public User getById(Long id) {
// 1、从本地缓存获取
User o = localCache.get(id+"");
return o;
}
}
总结
能够高效的读取的同时,提供了大量api方便我们控制本地缓存的数据量及冷数据淘汰;我们充分的学习这些特性能够帮助我们在业务开发中更加轻松灵活,在空间与时间上找到一个平衡点。