TIL

24.08.20 TIL - Redis in Spring

개발공명 2024. 8. 21. 01:08

 

오늘 배운 것

  • Spring Data Repository

 

Spring Data Repository

Spring Data가 가지고 있는 Repository 객체 사용하는 것

 

@RedisHash 사용해 Repository 만들고 사용하는 것

 

Java 객체를 Redis에 손쉽게 CRUD 할 수 있음

 

 

사용법

Spring Data의 JpaRepository 사용과 유사

 

JPA에서는 DB에 저장할 엔티티에 @Entity annotation 붙임

 

Redis에 저장될 클래스에는 @RedisHash(key) annotation 붙임

 

@RedisHash 안에 Redis key를 적는 것

 

JPA의 Entity

@Entity
public class Item {
    @Id
    private Long id;
    private String name;
    private String description;
    private Integer price;
}

 

Redis의 클래스

@RedisHash("item")
public class Item {
    @Id
    private Long id;
    private String name;
    private String description;
    private Integer price;
}

 

 

JPA에서는 DB에 저장하기 위해 JpaRepository를 구현한 Repository 클래스 생성

 

Redis에서는 Redis에 저장하기 위해 CrudRepository를 구현한 Repository 클래스 생성

 

JPA의 JpaRepository

public interface ItemRepository extends JpaRepository<Item, Long> {}

 

Redis의 CrudRepository

public interface ItemRepository extends CrudRepository<Item, Long> {}

 

사용도 비슷하게 하면 된다. 

 

CrudRepository에 구현된 메서드들을 사용해서 쉽게 Redis에 value를 저장하는 것이다. 

@Autowired
private ItemRepository itemRepository;

Item item = Item.builder()
		.id(1L)
                .name("keyboard")
                .description("Mechanical Keyboard Expensive")
                .build();

// Create
itemRepository.save(item);

// Read
Item item = itemRepository.findById(1L).orElseThrow();

// Update
item.setId(2L);
itemRepository.save(item);

// Delete
itemRepository.deleteById(2L);

 

 

결과

이렇게 Redis에 Item을 넣으면 아래와 같이 저장이 된다. 

 

Redis에 sets와 hash tables가 생성이 된다. 

 

sets에는 어떤 Item들이 현재 Redis에 저장되어 있는지 tracking 하기 위한 것이다. 

 

sets에는 Item의 id들의 집합이 들어가 있다.

 

그리고 hash tables에는 실제 Item의 데이터들이 들어가 있다. 

 

@RedisHash(key)에 들어있던 key = 여기서는 Item + id 해서 hash tables에 key로 넣는 것이다. 

 

그리고 그 value에는 Item의 데이터가 있는 것이다.

 

마무리

@RedisHash을 달아서 Redis에 넣을 클래스에서는 JPA의 entity는 Long id를 사용하는 것에 반해 id는 보통 String을 많이 사용한다. 

 

id를 String으로 사용하면 UUID가 자동으로 배정된다. 

 

Repository를 사용하는 것은 CRUD작업을 손쉽게 만들 수 있다,

 

또한 익숙한 Spring Data JPA와 유사하다는 장점이 있다. 

 

하지만 Redis의 다른 자료형, 이런 자료형들을 활용한 복잡한 기능을 만드는데에는 한계가 있다. 

 

왜냐하면 CrudRepository가 가지고 있는 메서드만 사용하기 때문이다. 

 

따라서 Redis를 직접적으로 사용하고 싶다면 RedisTemplate 사용하는 것이 좋다. 

'TIL' 카테고리의 다른 글

24.08.22 TIL - 캐싱  (0) 2024.08.23
24.08.21 TIL - session clustering  (0) 2024.08.23
24.08.19 TIL - Redis  (0) 2024.08.20
24.08.14 TIL - GitHub Actions  (1) 2024.08.16
24.08.13 TIL - Docker  (0) 2024.08.16