项目背景
缓存类目树,类目树下面几千个类目到达了5M,我直接用String的value存了进去.然后就redis查不动了,速度慢了下来.
还有一点就是我这个过程必须是可逆的,网上的加密方法很多.不符合我要求
管理工具直接卡死,可想我这个有多大
我找了解决方案
1,是将子集类目一层一层的存在数据库.我觉得太麻烦了,但是redis始终是缓存用的,不能作为持久用, 所以后期还是在数据库里面做一张表存这个玩意.
2,就是将这个value压缩,缩小后存入redis.取出来解压,我目前用的是这个方案.可以将valu压缩到5/1,提升了很大的速度.
有可能有其他的方法 我比较赶,秉承着开发精神先做出来再说.
下面这个工具类是我找的网上的.
/**
* 使用gzip压缩字符串
*
* @param originString 要压缩的字符串
* @return 压缩后的字符串
*/
public String compress(String originString) {
if (originString == null || originString.length() == 0) {
return originString;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (
GZIPOutputStream gzip = new GZIPOutputStream(out);
) {
gzip.write(originString.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return new sun.misc.BASE64Encoder().encode(out.toByteArray());
}
/**
* 使用gzip解压缩
*
* @param compressedString 压缩字符串
* @return
*/
public String uncompress(String compressedString) {
if (compressedString == null || compressedString.length() == 0) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] compressedByte = new byte[0];
try {
compressedByte = new sun.misc.BASE64Decoder().decodeBuffer(compressedString);
} catch (Exception e) {
e.printStackTrace();
}
String originString = null;
try (
ByteArrayInputStream in = new ByteArrayInputStream(compressedByte);
GZIPInputStream ginzip = new GZIPInputStream(in);
) {
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = ginzip.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
originString = out.toString();
} catch (IOException e) {
e.printStackTrace();
}
return originString;
}
用法,我这里是解压,压缩一样的,将你的对象或者存的数据,转成字符串,压缩一编,再传进去.(我刚开始想的是我能不能重复压缩,好像是不可行的)
@GetMapping(value = "/redis")
private Result redistest(@RequestParam(name = "site") String sites) {
List<String> siteList = Lists.newArrayList("SG", "MY", "VN", "ID", "PH");
Map<String, Object> map = new HashMap<>();
for (String site : siteList) {
String key = RedisConstants.CATEGORY_KEY + site;
if (redisUtil.hasKey(key)) {
Object o = redisUtil.get(key);
String uncompress = redisUtil.uncompress(o.toString());
LazadaCategoryTreeResult vo = JSONObject.parseObject(uncompress, LazadaCategoryTreeResult.class);
map.put(site, vo);
}
}
if (map.size() < siteList.size()){
return Result.errorMessage("加载类目树失败,请联系客服");
}
log.info("返回站点类目");
return Result.ok(map);
}