본문 바로가기
DB

[Redis/Java] HashMap 데이터 정수(int,long)로 저장하기

by 물고기고기 2023. 3. 5.

 

게시글 작성 시 조회수 관련 데이터를 Redis에 저장하려고 한다.

추후 어떤 필드가 추가될지 모르니 Redis에 hashMap 형태로 저장할 예정이다.

key(랜덤 생성) : {
	postId: 1,
	postView: 1
}

 

처음엔 코드를 아래처럼 field 부분에 데이터 이름과 value부분에 각각 long&int를 넣어주었는데

public void setViewCount(Long postId){

    HashOperations<String, Object, Object> hashOps = stringRedisTemplate.opsForHash();

    String key = UUID.randomUUID().toString();

    Map<String, Object> values = new HashMap<>();
    values.put("postId", postId);
    values.put("postView", 0);

    hashOps.putAll(key, values);
}

 

아래 에러가 발생하였다.

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')

잘 읽어보면 String 자리에 Integer를 넣으면 안된다는 말인데 위에 field값을 String으로 선언해주었는데 저기서 에러가 나는줄알고 뭐가 문제인지 한참 헤맸다.

 

코드에서 뭐가 문제냐고 물었더니 ChatGPT가 알려주었다.

Q.
now error is totally solved
but I have one question

    public void setViewCount(Long postId){

        HashOperations<String, Object, Object> hashOps = stringRedisTemplate.opsForHash();

        String key = UUID.randomUUID().toString();

        Map<String, Object> values = new HashMap<>();
        values.put("postId", postId.toString());
        values.put("postView", "0");

        hashOps.putAll(key, values);
    }

is this best practice? I want put value Integer or Long type not a string


A.
Redis stores all data as a string, so whenever you store numerical values in Redis, they are stored as strings. When retrieving values from Redis, you will need to convert them back to their original data types.

In your case, since you want to store the postId as a Long and postView as an Integer, it's fine to store them as strings in Redis. When retrieving the values, you can simply convert them back to their original data types.

So to answer your question, your code is fine as it is.

 

보니까 redis는 field값에 무조건 String이 들어가야하는 것 같다... 아래처럼 고쳐주니 에러가 안난다.

일단 String값으로 저장해주고 나중에 가져와서 쓸때 형변환을 해주는 것 같다.

    public void setViewCount(Long postId){

        HashOperations<String, Object, Object> hashOps = stringRedisTemplate.opsForHash();

        String key = UUID.randomUUID().toString();

        Map<String, Object> values = new HashMap<>();
        values.put("postId", postId.toString());
        values.put("postView", "0");

        hashOps.putAll(key, values);
    }

이렇게 쓰면 불편한데 개선할 방법이 있을것 같다.. 이건 추후 더 공부해볼 예정

댓글