SnappyUtils.java
2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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;
}
}
}