본문 바로가기

spring

[REDIS] Generic Redis Template 사용하기

https://stackoverflow.com/questions/23208010/drying-up-a-generic-redistemplate-in-spring-4

 

DRYing up a generic RedisTemplate in Spring 4

I've read that you can have @Autowired generics as of Spring 4, which is awesome. I have an abstract RedisService class in which I want to have @Autowired a generic RestTemplate, like so: public

stackoverflow.com

 

클래스 유형만큼 빈을 추가해서 template 사용해야 했다. 

 

 

 

코드는 아래. Redis 의 hash operation 에만 사용된다 

 

 

@Component
@RequiredArgsConstructor
public class RedisUtil {
    private HashOperations<String, String, Object> hashOperations;

     private final StringRedisTemplate redisTemplate;
    private final ModelMapper modelMapper;

    @PostConstruct
    public void init() {
        this.hashOperations = redisTemplate.opsForHash();
    }

    public <T> T get(String key, String hashKey, Class<T> type) {
        Object o = hashOperations.get(key, hashKey);
        return modelMapper.map(o, type);
    }

    public <T> List<T> getAll(String key, Class<T> type) {
        List<T> list = new ArrayList<>();
        for (Object o : hashOperations.values(key)) {
           list.add(modelMapper.map(o, type));
        }
        return list;
    }

    public boolean isEmpty(String key, String hashKey) {
        return hashOperations.hasKey(key, hashKey);
    }

    public void remove(String key, String hashKey) {
        hashOperations.delete(key, hashKey);
    }

}

 

 

아래의 테스트 코드에서 일단 출력해 보았는데 정상 작동 하는걸 확인할 수 있었다. 

model mapper 를 사용해서 바로 response 로 받을수 있어 편리했다.

public class RedisTest {
    private final RedisUtil redisUtil;

    @Test
    @Description("redis util 정상작동 테스트")
    public void RedisUtilExecutionTest() {
        redisUtil.getAll(SERVICE:001", BannerResponse.class)
                .stream().forEach(System.out::println);
        System.out.println(redisUtil.get("SERVICE:001", "1", BannerResponse.class));
        System.out.println(redisUtil.isEmpty("SERVICE:001", "1"));
        System.out.println(redisUtil.isEmpty("SERVICE:001", "2"));

    }
}

 

 

출처,참고 :

https://prodo-developer.tistory.com/157

https://stackoverflow.com/questions/47853416/how-to-autowire-redistemplatestring-object

 

반응형