栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

记录一个redis的key,和value过大的解决方案

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

记录一个redis的key,和value过大的解决方案

项目背景
缓存类目树,类目树下面几千个类目到达了5M,我直接用String的value存了进去.然后就redis查不动了,速度慢了下来.
还有一点就是我这个过程必须是可逆的,网上的加密方法很多.不符合我要求

管理工具直接卡死,可想我这个有多大


我找了解决方案
1,是将子集类目一层一层的存在数据库.我觉得太麻烦了,但是redis始终是缓存用的,不能作为持久用, 所以后期还是在数据库里面做一张表存这个玩意.
2,就是将这个value压缩,缩小后存入redis.取出来解压,我目前用的是这个方案.可以将valu压缩到5/1,提升了很大的速度.

有可能有其他的方法 我比较赶,秉承着开发精神先做出来再说.
下面这个工具类是我找的网上的.

	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());
	}


	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 siteList = Lists.newArrayList("SG", "MY", "VN", "ID", "PH");
		Map 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);
	}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/678094.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号