본문 바로가기
AI

자바 서버 → Snappy 압축 → 리액트 프론트에서 풀기

by david100gom 2025. 4. 28.

 


1. 서버 (Java) - Snappy 압축해서 전송하기

@RestController
@RequestMapping("/api")
public class CompressionController {

    @GetMapping("/compressed-data")
    public ResponseEntity<byte[]> getCompressedData() throws Exception {
        String originalData = "이것은 서버에서 보내는 테스트 데이터입니다!";

        byte[] compressed = Snappy.compress(originalData.getBytes(StandardCharsets.UTF_8));

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_ENCODING, "snappy") // (선택) 클라이언트에게 힌트 주기
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(compressed);
    }
}
  • 서버는 압축된 byte[] 를 그대로 전송합니다.
  • Content-Type을 application/octet-stream 으로 설정하는 게 깔끔합니다.
  • Content-Encoding: snappy 는 선택인데, 프론트가 이 헤더를 체크할 수도 있어요.

2. 프론트 (React) - 압축 해제하기

리액트에서는 Snappy 포맷을 풀어야 하니까 snappyjs 라이브러리를 사용합니다.

📦 2-1. 설치

npm install snappyjs

또는

yarn add snappyjs

✨ 2-2. 압축 해제 코드 (React)

import { uncompress } from 'snappyjs';

async function fetchAndDecompress() {
  const response = await fetch('/api/compressed-data');

  if (!response.ok) {
    throw new Error('Network response was not ok');
  }

  const compressedArrayBuffer = await response.arrayBuffer();
  const compressedUint8Array = new Uint8Array(compressedArrayBuffer);

  const uncompressedUint8Array = uncompress(compressedUint8Array);

  const decoder = new TextDecoder('utf-8');
  const text = decoder.decode(uncompressedUint8Array);

  console.log("압축 해제된 데이터:", text);
}

✔️ 핵심 흐름:

  • fetch()로 binary data를 받는다 (response.arrayBuffer()).
  • Uint8Array로 변환한다.
  • snappyjs.uncompress()로 압축을 푼다.
  • TextDecoder로 텍스트로 변환한다.

🧠 정리 그림

[서버 (Java)] 
    String -> Snappy 압축 -> byte[] 전송
            ↓
[리액트 (React)]
    fetch -> arrayBuffer -> Uint8Array
    -> snappyjs.uncompress()
    -> TextDecoder로 문자열 변환

🚨 주의할 점

  • Snappy 포맷 호환성: 서버와 클라이언트가 동일한 Snappy 포맷을 써야 합니다. (자바 Snappy와 snappyjs는 기본적으로 호환됩니다.)
  • CORS 설정: 서버가 다른 도메인이라면 CORS 허용해야 합니다.
  • 전송 데이터 크기: Snappy는 압축률이 높진 않지만 네트워크 전송 최적화에는 도움 됩니다.

추가로 해볼 수 있는 것

  • 압축 여부를 Accept-Encoding 요청 헤더로 협상
  • 에러 핸들링 강화
  • 대용량 스트리밍 (chunk 단위 압축/해제)

👉 여기까지 이해되셨나요?
필요하면 제가 "Spring Boot + React 통합 예제" 파일도 하나 짜드릴 수 있어요.
추가로 배포 환경에서는 어떻게 적용하면 좋은지 같은 것도 궁금하신가요? 🔥

728x90

댓글