Springboot Redis 연동

**** Redis를 도커로 실행중이라는 전제 하에 진행**

1. 연동

  1. build.gradle에 의존성 추가

    ...
    dependencies {
    	implementation 'org.springframework.boot:spring-boot-starter-amqp'
    	**implementation 'org.springframework.boot:spring-boot-starter-data-redis'**
    	implementation 'org.springframework.boot:spring-boot-starter-web''
    	compileOnly 'org.projectlombok:lombok'
    	developmentOnly 'org.springframework.boot:spring-boot-devtools'
    	annotationProcessor 'org.projectlombok:lombok'
    	testImplementation 'org.springframework.boot:spring-boot-starter-test'
    	testImplementation 'org.springframework.amqp:spring-rabbit-test'
    }
    ...
    
  2. application.yml에 연동 정보 설정

    Spring: 
    	redis:
    	    lettuce:
    	      pool:
    	        max-active: 5 # pool에 할당될 수 있는 최대 커넥션 수(음수: 무제한) 
    	        max-idle: 5 # pool의 idle 최대 커넥션 수(음수: 무제한)
    	        min-idle: 2 # pool에서 관리하는 idle 최소 커넥션 수
    	    host: 127.0.0.1
    	    port: 6379
    
  3. Redis 구성 클래스(RedisConfig.java) 작성

    package com.apple.api.redis.config;
    
    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;
    	
    //	@Value("${spring.redis.password}")
    //	private String password;
    	
    // 커넥션 설정
    	@Bean
    	public RedisConnectionFactory redisConnectionFactory() {
    		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
    		redisStandaloneConfiguration.setHostName(host);
    		redisStandaloneConfiguration.setPort(port);
    //		redisStandaloneConfiguration.setPassword(password);
    		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;
    	}
    	
    }
    
    package com.apple.api.redis.config;
    
    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;
    	}
    	
    }
    
  4. 컨트롤러(RedisController.java) 작성

    package com.apple.api.redis.controller;
    
    import java.util.Map;
    
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.ValueOperations;
    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.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/redis")
    public class RedisController {
    
    	private final RedisTemplate<String, String> redisTemplate;
    
    	public RedisController(RedisTemplate<String, String> redisTemplate) {
    		this.redisTemplate = redisTemplate;
    	}
    	
    // set
    	@PostMapping("")
    	public String setRedisKey(@RequestBody Map<String, String> req){
    		ValueOperations<String, String> vop = redisTemplate.opsForValue();
    		try {
    			// Redis Set Key-value
    			vop.set(req.get("key").toString(), req.get("value").toString());
    			return "set message success";
    		} catch (Exception e) {
    			return "set message fail";
    		}
    	}
    	
    // get
    	@GetMapping("/{key}")
        public String getRedisKey(@PathVariable String key) {
            ValueOperations<String, String> vop = redisTemplate.opsForValue();
            return vop.get(key);
        }
    	
    }
    
  5. Postman에서 데이터 저장해보기

    Untitled

    컨트롤러에 설정한 성공 시 리턴 값이 Response에 출력되면 성공

  6. 잘 저장됐는지 볼까용

    1. PostMan에서 확인

      ~/redis/{조회할 키}

      Untitled

    2. redis-cli에서 확인

      docker exec -it ***letsj_compose-redis_1*** redis-cli

      • 저장된 모든 키 조회

        Untitled

      • 저장되어 있는 키로 조회

        Untitled

.