3.캐시 적용해 성능 개선하기

Alex·2024년 7월 1일
0

성능 개선

목록 보기
2/9
@RestController
public class HashController {

    private final Map<String, String> cashHashResult = new ConcurrentHashMap<>();

    @GetMapping("/no-cache-hash-string")
    public String noCacheHashString(@RequestParam String input) {
        return calculateHash(input);
    }

    @GetMapping("/cached-hash-string")
    public String cachedHashString(@RequestParam String input) {
        if (cashHashResult.containsKey(input)) {
            return cashHashResult.get(input);
        }

        String hashedResult = calculateHash(input);
        cashHashResult.put(input, hashedResult);
        return hashedResult;
    }
    
    
     private String calculateHash(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");

            for (int i = 0; i < 50000; i++) {
                byte[] bytes = input.getBytes();
                byte[] hashedBytes = md.digest(bytes);
                input = bytesToHex(hashedBytes);
                md.reset();
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return input;
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte aByte : bytes) {
            result.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
        }
        return result.toString();
    }
    

numbers라는 csv파일과

config:
  target: 'http://localhost:8080'
  phases:
    - duration: 60
      arrivalRate: 30
  payload:
    path: "numbers.csv"
    fields:
      - "number"
scenarios:
  - name: "get hash"
    flow:
      - get:
          url: "/no-cache-hash-string?input={{ number }}"
#          url: "/cached-hash-string?input={{ number }}"

이 테스트 시나리오를 이용해본다.

캐시를 사용하지 않을 때는 위처럼 지연시간이 크게 치솟는 경우가 많았다.

내 노트북 성능의 문제가 크겠지만, 이 작업을 하는데만 450초가 걸렸다.

캐시를 사용하니 작업이 90초만에 끝났다.

지연시간은 처음에만 치솟다가 그 이후로는 캐시덕분에 안정화됐다.
강사님의 경우에는 3~40초부터는 거의 지연시간이 없었는데 내 노트북에서는 지연시간이 있는걸 보면.... 노트북 성능의 문제인가 싶다

캐시를 쓸 때 문제는
서버간 캐시 공유문제(메모리에 올리기 때문에) 캐시의 신선도문제가 발생할 수 있다고 한다.

멜론 top100차트는 오늘과 어제가 다를 수 있기 때문에 신선하지 않는 캐시 결과를 가져갈 수 있다.

profile
답을 찾기 위해서 노력하는 사람

0개의 댓글