通过Redis或Caffeine存储入json型String,通过JSON.parseObject自动类型转化之后,数值会优先转为Intage,如果存入的字符值大于Intage最大值,会自动转为Long型;
需求是:实要取出时数值类型值为Long;
public static void put(String key, Map val) {
cache.put(key, JSONObject.toJSONString(val));
}
public static Optional<Map> get(String key) {
String value = cache.getIfPresent(key);
Map maps = JSON.parseObject(value, Map.class);
return Optional.ofNullable(maps);
}
在获取缓存时,使用TypeReference强制将存储转为指定类型;
Map maps = JSON.parseObject(value, new TypeReference<Map<Long, String>>() {}, Feature.InitStringFieldAsEmpty);
CaffeineUtil.java
public class CaffeineUtil {
public static Cache<String, String> cache = Caffeine.newBuilder()
.initialCapacity(800)
.maximumSize(2000)
.expireAfterWrite(Duration.ofMinutes(60))
.build();
public static Optional<Map> get(String key) {
String value = cache.getIfPresent(key);
//会将存入的Map中Long对象自动转化为Integer型
//但如果值超出了Integer的最大值,会自动转为Long型
//Map maps = JSON.parseObject(value, Map.class);
//强制将存储转为Map<Long, String>
Map maps = JSON.parseObject(value, new TypeReference<Map<Long, String>>() {}, Feature.InitStringFieldAsEmpty);
return Optional.ofNullable(maps);
}
public static void put(String key, Map val) {
cache.put(key, JSONObject.toJSONString(val));
}
}
TestCaffeineController.java
public class TestCaffeineController {
@RequestMapping("/testCaffeine")
public Object testCaffeine(Long userId){
String userImg = this.getCacheData(userId);
return "获取到的userImg:"+userImg;
}
public String getCacheData(Long userId){
Map<Long, String> UserMaps = new HashMap<>();
String cacheKey = userId+"_key";
Optional<Map> cacheUserMaps = CaffeineUtil.get(cacheKey);
if(cacheUserMaps.isPresent()){
UserMaps = cacheUserMaps.get();
}else{
JSONArray userArray = new JSONArray();
JSONObject object1= new JSONObject();
object1.put("id", 1l);
object1.put("imgUrl", "aaaaaaa");
JSONObject object2= new JSONObject();
//因为该值已经超过Intage型最大值,在从缓存中取出时会自动转成Long类型
object2.put("id", 234567899999l);
object2.put("imgUrl", "bbbbbbb");
userArray.add(object1);
userArray.add(object2);
if(CollectionUtils.isNotEmpty(userArray)){
UserMaps = userArray.stream().collect(Collectors.toMap(o -> ((JSONObject)o).getLong("id"), o -> ((JSONObject)o).getString("imgUrl")));
CaffeineUtil.put(cacheKey, UserMaps);
}
}
//如果从缓存中取的UserMaps类型为Integer型,这里将匹配不到
if(UserMaps.containsKey(userId)) {
System.out.println("存在该值.");
return UserMaps.get(userId);
}else{
System.out.println("不存在该值.");
}
return null;
}
}