淘宝做女鞋在哪个网站找货,优秀电商网站,国内重大新闻20条,江苏建设科技网站通过Redis或Caffeine存储入json型String#xff0c;通过JSON.parseObject自动类型转化之后#xff0c;数值会优先转为Intage#xff0c;如果存入的字符值大于Intage最大值#xff0c;会自动转为Long型#xff1b; 需求是#xff1a;实要取出时数值类型值为Long#xff1…通过Redis或Caffeine存储入json型String通过JSON.parseObject自动类型转化之后数值会优先转为Intage如果存入的字符值大于Intage最大值会自动转为Long型 需求是实要取出时数值类型值为Long
1、写入Caffeine缓存 public static void put(String key, Map val) {cache.put(key, JSONObject.toJSONString(val));}2、获取Caffeine缓存 public static OptionalMap get(String key) {String value cache.getIfPresent(key);Map maps JSON.parseObject(value, Map.class);return Optional.ofNullable(maps);}3、解决方法 在获取缓存时使用TypeReference强制将存储转为指定类型 Map maps JSON.parseObject(value, new TypeReferenceMapLong, String() {}, Feature.InitStringFieldAsEmpty);4、完整样例
CaffeineUtil.java
public class CaffeineUtil {public static CacheString, String cache Caffeine.newBuilder().initialCapacity(800).maximumSize(2000).expireAfterWrite(Duration.ofMinutes(60)).build();public static OptionalMap get(String key) {String value cache.getIfPresent(key);//会将存入的Map中Long对象自动转化为Integer型//但如果值超出了Integer的最大值会自动转为Long型//Map maps JSON.parseObject(value, Map.class);//强制将存储转为MapLong, StringMap maps JSON.parseObject(value, new TypeReferenceMapLong, 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){MapLong, String UserMaps new HashMap();String cacheKey userId_key;OptionalMap 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;}
}