Cacheable KeyGenerator

빛물·2022년 7월 31일
0
post-thumbnail

@Cacheable의 Key를 KeyGenerator를 이용해 생성할 수 있으며, 전달된 파라미터를 통해 유일키를 생성할 수 있다.

public class CustomKeyGenerator implements KeyGenerator {
    public Object generate(Object target, Method method, Object... params) {
        return String.format("%s_%s_%s", target.getClass().getSimpleName() ,method.getName(),StringUtils.arrayToDelimitedString(params, "_"));;
    }
}

하지만 String 클래스의 경우 유일키 생성이 가능하지만 파라미터가 객체(Object)형태일 경우 hash값으로 인해 동일한 key가 생성되지 않아 캐싱의 의미가 없어진다.
이를 해결하기 위해 파라미터를 바이트로 변환하여 Key를 생성하면 동일한 파라미터에 대해서 동일한 Key를 생성할 수 있다.

public class CustomKeyGenerator implements KeyGenerator {
    public Object generate(Object target, Method method, Object... params) {
        //레디스 키 생성 시 객체를 모두 수용하기 위해 바이트로 변환하여 키생성
        byte[] b = objectStreamSerializer(params);
        return String.format("%s_%s_%s", target.getClass().getSimpleName() ,method.getName(), new String(b));
    }

    public byte[] objectStreamSerializer(Object object) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = null;

        byte[] result;
        try {
            out = new ObjectOutputStream(bos);
            out.writeObject(object);
            result = bos.toByteArray();
        } catch (IOException e) {
            throw new BaseException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                throw new BaseException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e.getMessage());
            }

            try {
                bos.close();
            } catch (IOException e) {
                throw new BaseException(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), e.getMessage());
            }
        }

        return result;
    }
}
profile
천천히..

0개의 댓글