스프링 부트가 있는 Redis

Nov 28 2022
소개
이 게시물에서 우리는 Redis에 대해 논의할 것입니다. Redis는 여러 용도로 사용할 수 있는 키-값 기반 NoSQL 데이터베이스입니다. 오픈 소스이며 InMemory 데이터 구조 저장소입니다.
Unsplash에 있는 Josh Glauser의 사진

이 게시물에서 우리는 Redis 에 대해 논의할 것입니다. Redis는 여러 용도로 사용할 수 있는 키-값 기반 NoSQL 데이터베이스입니다. 오픈 소스이며 InMemory 데이터 구조 저장소입니다. Redis는 목록, 집합, 지도 및 정렬된 집합과 같은 모든 기본 데이터 구조를 지원하기 때문입니다.

Redis를 사용하여 채팅 애플리케이션, 세션 스토리지 애플리케이션, 게임 대시보드 등과 같은 다양한 종류의 애플리케이션을 개발할 수 있습니다.

Redis를 배우고 싶다면 먼저 Redis에서 데이터를 저장하고 가져올 수 있는 명령과 별도로 Redis가 지원하는 다양한 데이터 구조에 대해 이해하십시오.

몇 가지 중요한 명령

Redis는 String, Set, Sorted Set, List 및 HashMap을 키 값으로 지원합니다. 다음은 다양한 데이터 구조를 이해하기 위한 몇 가지 기본 명령입니다.

String 
SET foo bar (foo is key, bar is value)
GET foo
bar
HashMap

HMSET student name: "shubham" age: 25
HGETALL student
List
LPUSH product car
LPUSH product bike

LRANGE product 0 10
Set
SADD product car
SADD product bike

SMEMBERS product

Redis 사용 사례

  1. Redis는 키-값 기반 NoSQL 데이터베이스로 사용할 수 있습니다.
  2. Redis는 캐시 공급자로 사용할 수 있습니다.
  3. Redis는 이벤트 처리에 사용되는 게시자 및 구독자로 사용할 수 있습니다.
  4. Redis는 세션 저장소로 사용할 수 있습니다.
  5. Redis는 채팅 애플리케이션에서 사용할 수 있습니다.

따라서 이 글을 읽은 후 관심이 생겨 Redis에서 실습을 하고 싶다면 시스템에 Redis 서버를 설정하십시오.

  1. 없는 경우 시스템에 homebrew를 설치합니다.
  2. 아래 명령을 순차적으로 실행
  3. brew install redis
    
    After succesfull installation 
    
    brew services start redis
    
    After starting redis if you want to try above commands
    
    redis-cli
    
    To test whether redis server is working
    
    PING
    
    If yu get PONG then its connected
    
    If you want to monitor which all commands are getting executed on redis
    
    redis-monitor
    

따라서 이후에 다른 시스템에서 Redis를 사용하려면 Redis 서버와 상호 작용할 클라이언트가 필요합니다.

이제 이 파트에서는 ​​Redis를 스프링 부트와 함께 사용하여 NoSQL DB로 사용하는 방법에 대해 알아보겠습니다.

설정

첫 번째 단계는 스프링 초기화 프로그램에서 샘플 스프링 부트 프로젝트를 생성하고 spring-boot-starter-data-redis 종속성 을 추가하는 것 입니다.

이제 프로젝트를 즐겨찾는 IDE로 가져온 후 패키지와 클래스를 만듭니다.

첫 번째 클래스는 구성에 대한 것입니다. Redis용 드라이버가 두 개 있습니다. 하나는 Jedis이고 다른 하나는 상추입니다(지연하게 초기화되며 성능 측면에서도 더 좋습니다.)

드라이버와는 별도로 Redis 서버에서 작업을 수행하기 위한 템플릿이 필요합니다. 이는 나머지 작업을 수행하기 위한 RestTemplate과 유사한 방식입니다.

package com.redisexample.redisdemo.config;

import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
//@EnableRedisRepositories
public class AppConfig {

    //There are two ways of creating driver, one is jedis another is lettuce,
    //lettuce is bit lazy in intialization so it creates beans  lazily
//It is using default host and port
    @Bean
    RedisConnectionFactory jedisConnectionFactory() {
        return new LettuceConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new JdkSerializationRedisSerializer());
        template.setValueSerializer(new JdkSerializationRedisSerializer());
        template.setEnableTransactionSupport(true);
        template.afterPropertiesSet();
        return template;
    }

    //For setting host and port
//    @Bean
//    JedisConnectionFactory jedisConnectionFactory() {
//        JedisConnectionFactory jedisConFactory
//                = new JedisConnectionFactory();
//        jedisConFactory.setHostName("localhost");
//        jedisConFactory.setPort(6379);
//        return jedisConFactory;
//    }

}

엔터티 클래스 만들기

@RedisHash("student") // this is a set so we can use set command to see data via redis cli
public class Student {

    public enum Gender {
        MALE, FEMALE
    }

    private Long id;
    private String name;
    private int age;
    private String city;

    //getters and setters
}

@Repository
public interface StudnetRepo extends CrudRepository<Student, Long> {

}

package com.redisexample.redisdemo.controller;

import com.redisexample.redisdemo.model.Student;
import com.redisexample.redisdemo.repo.StudnetRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudnetRepo studnetRepo;

    @PostMapping
    public void saveStudent(@RequestBody Student student){
        studnetRepo.save(student);
    }

    @GetMapping
    public Iterable<Student> getStudent(){
        return studnetRepo.findAll();
    }
}

따라서 이것은 스프링 부트 애플리케이션에서 Redis를 DB로 사용하는 간단한 예입니다.

다음 포스팅에서는 Redis를 Cache Provider로 사용하는 방법에 대해 알아보겠습니다.

읽어 주셔서 감사합니다!!