01.Redis

이지훈·2024년 5월 31일
0

Redis

목록 보기
1/2
post-thumbnail

캐싱 전략

의존성 관리, docker 컨테이너 등록

도커 명령

docker-compose -f docker-compose-redis.yml up -d
docker exec -it redis-pub-container redis-cli
docker commit -m "redis-set" redis-pub-container 도커허브아이디/redis
docker image push  도커허브아이디/redis
docker exec -it redis-pub-container redis-cli ping
docker logs -f web

applications.properties

#redis
#spring.data.redis.host=localhost
spring.data.redis.host=redis-pub-container
spring.data.redis.port=6379
spring.data.redis.password=1234
services:
  web_service:
    container_name: web
    image: chaterbox/security
    ports:
      - 9000:9000
    depends_on:
      - redis
    networks:
      - app-network

  # 서비스명
  redis:
    # 사용할 이미지
    image: redis:latest
    # 컨테이너명
    container_name: redis-pub-container
    # 접근 포트 설정(컨테이너 외부:컨테이너 내부)
    hostname: test
    ports:
      - 6379:6379
    # 스토리지 마운트(볼륨) 설정
    volumes:
      - ./redis/data:/data
      - ./redis/conf/redis.conf:/usr/local/conf/redis.conf
    # 컨테이너에 docker label을 이용해서 메타데이터 추가
    labels:
      - "name=redis"
      - "mode=standalone"
    # 컨테이너 종료시 재시작 여부 설정
    restart: always
    command: redis-server /usr/local/conf/redis.conf
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

Redis 설정

package com.example.jhta_3team_finalproject.cache;


import com.example.jhta_3team_finalproject.domain.chat.ChatMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@EnableCaching
@Configuration
public class RedisCacheConfig {

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

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

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

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

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory());

        // 일반적인 key:value의 경우 시리얼라이저
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());

        // Hash를 사용할 경우 시리얼라이저
        // redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // redisTemplate.setHashValueSerializer(new StringRedisSerializer());

        // 모든 경우
        // redisTemplate.setDefaultSerializer(new StringRedisSerializer());

        return redisTemplate;
    }

    @Bean
    public RedisTemplate<String, ChatMessage> messageRedisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, ChatMessage> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(ChatMessage.class)); // ChatDto 클래스를 직렬화
        return redisTemplate;
    }
}

RedisUtils - Redis DB를 편하게 다루기 위해서 사용 예정

package com.example.jhta_3team_finalproject.cache;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisUtils {

    private final RedisTemplate<String, Object> redisTemplate;

    public RedisUtils(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void setData(String key, String value,Long expiredTime){
        redisTemplate.opsForValue().set(key, value, expiredTime, TimeUnit.MILLISECONDS);
    }

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

    public void deleteData(String key){
        redisTemplate.delete(key);
    }
}

RedisController - 요청을 통해 데이터가 잘 들어왔는지 확인

package com.example.jhta_3team_finalproject.controller;

import lombok.RequiredArgsConstructor;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class RedisController {

    private final RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/redisTest")
    public ResponseEntity<?> addRedisKey() {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set("test-key-2", "test-value-2");
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
    @RequestMapping("/redisTest/{key}")
    public ResponseEntity<?> getRedisKey(@PathVariable String key) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String value = valueOperations.get(key);
        return new ResponseEntity<>(value, HttpStatus.OK);
    }
}

테스트 URL 요청

http:localhost:9091/redisTest 			 // addRedisKey
http:localhost:9091/redisTest/test-key-2 // getRedisKey 

redis-cli 명령어

127.0.0.1:6379> keys *
1) "test-key-2"
127.0.0.1:6379> get "test-key-2"
"test-value-2"
profile
ziru.log

0개의 댓글

관련 채용 정보