SnappyUtils.java 2 KB
package com.yoho.search.common.utils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xerial.snappy.Snappy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class SnappyUtils {

	private static final Logger logger = LoggerFactory.getLogger(SnappyUtils.class);

	/**
	 * 压缩
	 * 
	 * @param text
	 * @return
	 */
	public static String compress(String unCompressedVal) {
		try {
			byte[] compressVal = Snappy.compress((unCompressedVal).getBytes(StandardCharsets.UTF_8));
			return new String(compressVal, StandardCharsets.ISO_8859_1);
		} catch (IOException e) {
			logger.error("Snappy压缩失败:[func={}][unCompressedVal={}][message={}]", "compress", unCompressedVal, e.getMessage());
			return null;
		}
	}
	
	/**
	 * 压缩
	 * @param obj
	 * @return
	 */
	public static String compress(Object obj){
		if(null==obj){
			return StringUtils.EMPTY;
		}
	    //序列化使用json,并压缩缓存对象
		String value=null;
		if(obj instanceof String){
			value=(String)obj;
		}else{
			value=JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);
		}
		try {
			byte[] compressVal = Snappy.compress(value.getBytes(StandardCharsets.UTF_8));
			String compressStr = new String( compressVal, StandardCharsets.ISO_8859_1);
			return compressStr;
		} catch (Exception e) {
			//do nothing
			logger.warn("compress the object failed",e);
			return StringUtils.EMPTY;
		} 
	}

	/**
	 * 解压缩
	 * 
	 * @param compressVal
	 * @return
	 */
	public static String uncompress(String compressedVal) {
		try {
			byte[] unCompressVal = Snappy.uncompress((compressedVal).getBytes(StandardCharsets.ISO_8859_1));
			return new String(unCompressVal, StandardCharsets.UTF_8);
		} catch (IOException e) {
			logger.error("缓存解压缩失败:[func={}][compressedVal={}][message={}]", "uncompress", compressedVal, e.getMessage());
			return null;
		}
	}

}