欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java 字符串壓縮與解壓的開發(fā)記錄

 更新時間:2022年06月09日 11:17:28   作者:你好像很好吃a  
這篇文章主要介紹了Java 字符串壓縮與解壓的開發(fā)記錄,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

1、場景:

由于數(shù)據(jù)庫字段長度有限,并且不能隨意的修改數(shù)據(jù)庫字段的配置,數(shù)據(jù)庫的某個字段設(shè)置的長度可能在設(shè)置初期是滿足需求的,后期由于業(yè)務(wù)變更或業(yè)務(wù)量增大導(dǎo)致該字段存儲的數(shù)據(jù)增長,落庫時可能因?yàn)樵撟侄螖?shù)據(jù)長度過長導(dǎo)致落庫失敗,基于這種場景我們就有必要進(jìn)行字符串的壓縮,然后再進(jìn)行落庫,而落庫后取出數(shù)據(jù)使用時再進(jìn)行解壓即可。

2、CompressUtil類:

使用Java8中的gzip來進(jìn)行實(shí)現(xiàn)

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
 * 壓縮String的工具類
 */
@Slf4j
public class CompressUtil {
    /**
     * 使用gzip壓縮字符串
     * @param str 要壓縮的字符串
     * @return 壓縮后的字符串
     */
    public static String compress(String str) {
        if (str == null || str.length() <= 0) {
            return str;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
            gzip.write(str.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            log.error("字符串壓縮失敗str:{},錯誤信息:{}", str, e.getMessage());
            throw new RuntimeException("字符串壓縮失敗");
        }
        return Base64.encodeBase64String(out.toByteArray());
    }
    /**
     * 使用gzip解壓縮
     * @param compressedStr 壓縮字符串
     * @return 解壓后的字符串
     */
    public static String uncompress(String compressedStr) {
        if (compressedStr == null || compressedStr.length() <= 0) {
            return compressedStr;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in;
        GZIPInputStream gzip = null;
        byte[] compressed;
        String decompressed;
        try {
            compressed = Base64.decodeBase64(compressedStr);
            in = new ByteArrayInputStream(compressed);
            gzip = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int offset;
            while ((offset = gzip.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            decompressed = out.toString(StandardCharsets.UTF_8.name());
        } catch (IOException e) {
            log.error("字符串解壓失敗compressedStr:{},錯誤信息:{}", compressedStr, e.getMessage());
            throw new RuntimeException("字符串解壓失敗");
        } finally {
            if (gzip != null) {
                try {
                    gzip.close();
                } catch (IOException ignored) {
                }
            }
            try {
                out.close();
            } catch (IOException ignored) {
            }
        }
        return decompressed;
    }
}

3、注意點(diǎn):

1)CompressUtil在壓縮過程和解壓過程使用統(tǒng)一字符集,防止壓縮和解壓過程因?yàn)樽址煌瑢?dǎo)致結(jié)果與實(shí)際預(yù)期不符;

2)在web項(xiàng)目中,服務(wù)器端將加密后的字符串返回給前端,前端再通過ajax請求將加密字符串發(fā)送給服務(wù)器端處理的時候,在http傳輸過程中會改變加密字符串的內(nèi)容,導(dǎo)致服務(wù)器解壓壓縮字符串發(fā)生異常;

而CompressUtil壓縮和解壓過程中使用Base64.encodeBase64String和Base64.decodeBase64進(jìn)行編碼和解碼,可以完全解決上述問題。

3)壓縮/解壓失敗怎么處理?
通過CompressUtil工具類可以看出,如果壓縮或解壓失敗,過程發(fā)生異常,則會拋出一個運(yùn)行時異常給調(diào)用方,方便調(diào)用方及時感知并處理;

具體如何處理要看具體的業(yè)務(wù)場景,我這邊是在MQ消費(fèi)者中調(diào)用,在MQ中統(tǒng)一捕獲異常,所以如果壓縮失敗會進(jìn)行重試,如果重試多次依然失敗,我這邊會進(jìn)行報警打印日志,內(nèi)部人會去處理。

4、單元測試:

import org.junit.Test;
public class CompressUtilTest {
    @Test
    public void test1() {
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = 0;i < 100000;i++) {
            stringBuilder.append("1");
        }
        System.out.println(stringBuilder.toString().length());
        String compress = CompressUtil.compress(stringBuilder.toString());
        System.out.println("compress="+compress);
        System.out.println(compress.length());
        String uncompress = CompressUtil.uncompress(compress);
        System.out.println(uncompress.length());
        System.out.println("uncompress=" + uncompress);
    }
}

測試1:100000壓縮以后為180,解壓后也可以正常返回原字符串

測試2:把壓縮字符串長度改為1000再試一次,壓縮后長度為40

壓縮比例還是很高的,親測可用?。?!

到此這篇關(guān)于Java 字符串壓縮與解壓的開發(fā)記錄的文章就介紹到這了,更多相關(guān)Java 字符串壓縮 解壓內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論