티스토리 뷰

1. docker-compose로 Redis 띄우기

Docker로 Redis를 띄우기 위해 docker-compose.yml 파일을 아래와 같이 작성합니다.

version: "3"
services:
  redis:
    image: redis:alpine
    command: redis-server --port 6379
    container_name: redis_boot
    hostname: redis_boot
    labels:
      - "name=redis"
      - "mode=standalone"
    ports:
      - "6379:6379"

 

아래 명령을 통해 Redis를 띄웁니다.

$ docker-compose up -d

 

2. redis 의존 추가

build.gradle 파일에 아래와 같이 의존을 추가합니다.

dependencies {
    ...
    
    // redis
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    
    ...
}

 

3. application.yml에 redis 설정

spring:
    redis:                                        
      lettuce:                                    
        pool:                                     
          max-active: 5 # pool에 할당될 수 있는 커넥션 최대수  
          max-idle: 5 # pool의 'idle' 커넥션 최대수      
          min-idle: 2                             
      host: localhost                             
      port: 6379

 

4. RedisConfig 작성

import org.springframework.beans.factory.annotation.Value;
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.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(host);
        redisStandaloneConfiguration.setPort(port);
        return new LettuceConnectionFactory(redisStandaloneConfiguration);
    }

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

}

 

5. 테스트를 위한 Controller 작성

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController; 

@RestController
public class RedisController {     
    @Autowired    
    private RedisTemplate<String, String> redisTemplate;     
    
    @PostMapping("/redisTest")    
    public ResponseEntity<?> addRedisKey() {        
    	ValueOperations<String, String> vop = redisTemplate.opsForValue();        
        vop.set("yellow", "banana");        
        vop.set("red", "apple");        
        vop.set("green", "watermelon");        
        return new ResponseEntity<>(HttpStatus.CREATED);    
    }     
    
    @GetMapping("/redisTest/{key}")    
    public ResponseEntity<?> getRedisKey(@PathVariable String key) {        
    	ValueOperations<String, String> vop = redisTemplate.opsForValue();        
        String value = vop.get(key);        
        return new ResponseEntity<>(value, HttpStatus.OK);    
    }
}

 

6. postman으로 테스트 해보기

서버를 실행하고 [POST] http://localhost:7070/api/redisTest 로 요청을 보내는 경우 Redis에 데이터가 저장되고, [GET] http://localhost:7070/api/redisTest/yellow 등으로 요청을 보내면 저장한 key의 value 값이 출력됩니다. (참고로 port나 context-path 등은 달라질 수 있습니다...)

 

참고

- medis 설치

- https://oingdaddy.tistory.com/239

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