티스토리 뷰

 

 

앞선 글에서는 캐시에 단순 String만 저장했다.

 

그런데 작업을 하다보면 한 줄의 단순한 String 보다는 더 많은 정보를 담고싶기 때문에 Object를 저장하고 싶을 것이다.

 

이 내용을 정리해봤다.

 

1. 저장하기

객체를 스트림으로 변환 후 Byte[] 형태로 저장한다.

 

id는 기존 String을 저장하는 방식과 같이 UUID로 랜덤값을 생성했다.

public String saveObjectCache(ObjectVo value) {
    Cache cache = cacheManager.getCache("myCache");
    String id = UUID.randomUUID().toString();
    byte[] bytes = null;
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
         ObjectOutput out = new ObjectOutputStream(bos)) {
        out.writeObject(value);
        bytes = bos.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    }
    cache.put(id, bytes);
    return id;
}

여기서 중요한게 ObjectVo 객체이다.

@Getter @Setter
public class ObjectVo implements Serializable {
    private String message;
    private String description;
    private Integer messageNo;
}

반드시 Serializable을 implements 받아야한다.

 

객체를 스트림으로 변환하려면 직렬화(Serializable)가 필수이기 때문이다.

 

이와같이 만들었다면, 저장이 가능하다.

 

2. 불러오기

public CacheMessageVo getObjectCache(String id) {
    Cache cache = cacheManager.getCache("myCache");
    byte[] bytes = cache.get(id, byte[].class);
    ObjectVo result = null;
    try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
         ObjectInput in = new ObjectInputStream(bis)) {
        result = (CacheMessageVo) in.readObject();
    } catch (ClassNotFoundException | IOException e) {
        e.printStackTrace();
    }
    return result;
}

위와 같이 작성하면 불러 올 수 있다.

 

타입캐스팅을 내부에서 다해주었기 때문에, 외부에선 그냥 사용가능하다.

 

3. 사용하기

ObjectVo object = new ObjectVo();
object.setMessage("hello");
object.setMessageNo(122);
String id = cacheService.saveObjectCache(object);
ObjectVo cacheObject = cacheService.getCache(id);
cacheService.clearCache(id);
// 이후에 아래와 같이 접근 시 null값 출력
ObjectVo cacheObject2 = cacheService.getCache(id);

삭제도 스트링과 동일하게 작업하면 된다.

 

마치며

일단은 스프링부트에서 제공하는 org.springframework.cache.Cache 의 기능에 대해선 대부분 알아본 것 같다.

 

다음에 캐시에 대해 글을 작성하게 된다면, Redis를 썼거나 CDN에서 작업한게 아닐까 싶다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함