티스토리 뷰

1. 프로젝트 설정

먼저, 스프링 부트 프로젝트를 생성하고 Redis 관련 의존성을 추가합니다.

1.1. 스프링 부트 프로젝트 생성

Spring Initializr를 사용하여 프로젝트를 생성합니다. 필요한 의존성으로는 Spring Data Redis와 Lombok(선택 사항)을 추가합니다.

  • Spring Data Redis: Redis와의 통합을 위한 스프링 데이터 모듈
  • Lombok: 코드 간소화를 위한 라이브러리 (선택 사항)

1.2. pom.xml에 의존성 추가

Maven을 사용하는 경우, pom.xml 파일에 다음과 같이 의존성을 추가합니다.

<dependencies>
    <!-- Spring Boot Starter Data Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    <!-- Lombok (Optional) -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <scope>provided</scope>
    </dependency>

    <!-- Spring Boot Starter Web (Optional, for REST API) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

 

Gradle을 사용하는 경우, build.gradle 파일에 다음과 같이 의존성을 추가합니다.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    implementation 'org.springframework.boot:spring-boot-starter-web'
}

 

 

 

2. Redis 설정

스프링 부트에서 Redis를 사용하기 위해 application.properties 또는 application.yml 파일에 Redis 서버의 연결 정보를 설정합니다.

2.1. application.properties 파일 설정

# Redis 설정
spring.redis.host=localhost
spring.redis.port=6379

2.2. application.yml 파일 설정

spring:
  redis:
    host: localhost
    port: 6379

 

 

 

3. RedisTemplate 설정

Redis와 상호작용하기 위해 RedisTemplate을 설정합니다. 이는 Redis에 데이터를 저장하고 조회하는 데 사용됩니다.

3.1. RedisConfig 클래스 생성

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        return template;
    }
}

 

 

 

4. Redis 서비스 구현

Redis에 데이터를 저장하고 조회하는 서비스 클래스를 구현합니다.

4.1. RedisService 클래스 생성

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public void setValue(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public String getValue(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }
}

 

 

 

5. 컨트롤러 구현 (선택 사항)

REST API를 통해 Redis에 데이터를 저장하고 조회하는 컨트롤러를 구현할 수 있습니다.

5.1. RedisController 클래스 생성

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/redis")
public class RedisController {

    @Autowired
    private RedisService redisService;

    @PostMapping("/set")
    public String setValue(@RequestParam String key, @RequestParam String value) {
        redisService.setValue(key, value);
        return "Value set successfully";
    }

    @GetMapping("/get")
    public String getValue(@RequestParam String key) {
        return redisService.getValue(key);
    }
}

 

 

 

6. 애플리케이션 실행 및 테스트

스프링 부트 애플리케이션을 실행하고, Redis에 데이터를 저장하고 조회하는 API를 테스트합니다.

6.1. 애플리케이션 실행

mvn spring-boot:run

 

또는 IDE에서 SpringBootApplication 클래스를 실행합니다.

6.2. API 테스트

  • 데이터 저장: POST /redis/set?key=myKey&value=myValue
  • 데이터 조회: GET /redis/get?key=myKey

 

 

7. 추가 기능

  • 캐싱: 스프링 부트의 @Cacheable 어노테이션을 사용하여 메서드 결과를 Redis에 캐싱할 수 있습니다.
  • Pub/Sub: Redis의 Pub/Sub 기능을 사용하여 메시지 브로커로 활용할 수 있습니다.
  • 세션 저장: 스프링 세션을 Redis에 저장하여 분산 세션 관리가 가능합니다.

 

 

8. 참고 자료

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