02.Redis

이지훈·2024년 5월 31일
0

Redis

목록 보기
2/2
post-thumbnail

#npx scss 명령
npx sass --watch chat-skill-menu.scss chat-skill-menu.css

# redis-cli 실행
docker exec -it redis-pub-container redis-cli

# key 전체 확인
keys *

# list 전체 조회
lrange "{key}" 0 -1

# set 전체 조회
smembers "{key}"

# key 삭제
delete "{key}"

RedisCacheConfig.java

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;
    }
}

redisUtil.java

import com.example.jhta_3team_finalproject.domain.chat.ChatMessage;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
@Service
public class RedisUtils {

    private final RedisTemplate<String, ChatMessage> redisTemplate;

    public void setExpired(String key, Long expiredTime) {
        redisTemplate.expire(key, expiredTime, TimeUnit.DAYS);
    }

    public void setInitSets(String key, ChatMessage value) {
        redisTemplate.opsForSet().add(key, value);
    }

    public Set<ChatMessage> getSets(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    public boolean isKeyExists(String key) {
        return redisTemplate.hasKey(key);
    }

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

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

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

1주일 데이터를 Redis로 가져오기


import com.example.jhta_3team_finalproject.cache.RedisUtils;
import com.example.jhta_3team_finalproject.domain.chat.ChatMessage;
import com.example.jhta_3team_finalproject.mybatis.mapper.chat.ChatMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;

@Transactional
@Slf4j
@RequiredArgsConstructor
@Service
public class RedisService {

    private final ChatMapper dao;
    private final RedisUtils redisUtils;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    LocalTime localTime = LocalTime.of(0, 0, 0);

    /**
     * 2024-06-05, 1주일 전 데이터를 하루씩 가져와서 통합 리스트에 담기
     */
    public List<ChatMessage> getRedisChatMessage(ChatMessage chatMessage) {
        List<ChatMessage> oneWeekTotalList = new ArrayList<>();
        long num = chatMessage.getChatRoomNum();
        for (int dayCount = 7; dayCount >= 0; dayCount--) { // 오늘부터 1주일 전 기록까지 반복하여 하루씩 처리
            LocalDate localDate = LocalDate.now().minusDays(dayCount);
            LocalDateTime localDateTime = LocalDateTime.of(localDate, localTime);
            Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
            String dateStr = simpleDateFormat.format(date.getTime());
            String key = num + ":" + dateStr;
            List<ChatMessage> oneDayList = getChatMessageList(num, key, dateStr);
            oneWeekTotalList.addAll(oneDayList);
        }
        return oneWeekTotalList;
    }

    /**
     * 2024-06-05
     * true, 키가 있다면 레디스에서 가져와서 return
     * false, 키가 없다면 레디스에 올려준 후 해당 List 는 바로 return
     */
    private List<ChatMessage> getChatMessageList(long num, String key, String dateStr) {
        if (redisUtils.isKeyExists(key)) {
            log.info("RedisGet");
            Set<ChatMessage> chatMessageSet = redisUtils.getSets(key);
            List<ChatMessage> chatMessageList = new ArrayList<>(chatMessageSet);
            chatMessageList.sort(Comparator.comparing(ChatMessage::getMessageNum));
            return chatMessageList;
        } else {
            log.info("RdbGet");
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setChatRoomNum(num);
            chatMessage.setDateStr(dateStr);
            List<ChatMessage> chatMessageList = dao.redisSearchMessages(chatMessage);
            if (!chatMessageList.isEmpty()) {
                chatMessageList.forEach(chatMsg -> {
                    String roomKey = String.valueOf(chatMsg.getChatRoomNum());
                    String dateKey = simpleDateFormat.format(chatMsg.getSendTime());
                    String redisKey = roomKey + ":" + dateKey; // 방번호:날짜
                    Long expiredTime = 1L; // 만료 시간 1주일 부여
                    redisUtils.setInitSets(redisKey, chatMsg); // 키, 값
                    redisUtils.setExpired(redisKey, expiredTime);
                });
            }
            return chatMessageList;
        }
    }
}
profile
ziru.log

0개의 댓글

관련 채용 정보