Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
JuseungL committed Nov 26, 2024
1 parent 93f0e7a commit 205c8d8
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 95 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ public String healthCheck() {
@GetMapping("/redis")
public String redisConnectionCheck() {
// Redis에서 'id1' 키로 값을 가져옵니다.
String value = (String) redisUtil.getValue("id1");
String value = redisUtil.getObjectByKey("id1", String.class);

// Redis에서 가져온 값이 있을 경우 반환, 없으면 기본 메시지 반환
if (value != null) {
return "value";
return value;
} else {
return "No value found for key 'id1'";
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.drinkhere.infraredis.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

@Component
public class JsonComponent {

private ObjectMapper objectMapper;

@PostConstruct
public void init() {
objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
}

public String objectToJson(Object obj) {
String jsonStr = "";
try {
jsonStr = objectMapper.writeValueAsString(obj);
} catch (Exception e) {
new RuntimeException("ParsingException", e);
}
return jsonStr;
}

public <T> T jsonToObject(String json, Class<T> clazz) {
T obj = null;
try {
// 단순 문자열을 처리할 수 있도록 readValue를 명시적으로 호출
if (clazz == String.class) {
return clazz.cast(json); // 단순 문자열 그대로 반환
}
obj = objectMapper.readValue(json, clazz);
} catch (Exception e) {
throw new RuntimeException("ConvertException", e); // 예외를 던져 문제를 추적 가능하게 만듦
}
return obj;
}

}
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
package com.drinkhere.infraredis.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
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.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;


Expand All @@ -29,43 +23,18 @@ public class RedisConfig {

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

@Bean
public CacheManager redisCacheManager(
RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration configuration = RedisCacheConfiguration
.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair
.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair
.fromSerializer(new GenericJackson2JsonRedisSerializer()));

return RedisCacheManager.RedisCacheManagerBuilder
.fromConnectionFactory(redisConnectionFactory)
.cacheDefaults(configuration)
.build();
}

@Bean
public RedisMessageListenerContainer redisMessageListenerContainer(
RedisConnectionFactory redisConnectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(redisConnectionFactory);
return container;
}

@Bean
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) {
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setConnectionFactory(redisConnectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
return redisTemplate;
}
}
Original file line number Diff line number Diff line change
@@ -1,72 +1,35 @@
package com.drinkhere.infraredis.util;

import com.drinkhere.infraredis.config.JsonComponent;
import io.micrometer.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
@Component
public class RedisUtil {
// RedisTemplate은 Redis와 상호작용하는 다양한 작업을 제공하는 클래스
// 키는 String으로, 값은 Object 타입으로 저장될 수 있는 키-값 저장소로서 Redis와 작업
private final RedisTemplate<String, Object> redisTemplate;

/**
* 지정된 만료 시간과 함께 값을 Redis에 저장하는 메서드.
* 'key'에 해당하는 값 'val'을 지정된 시간 'time' 동안 Redis에 저장.
* 시간 단위는 'timeUnit'으로 설정.
* @param key Redis에 저장할 키.
* @param val Redis에 저장할 값.
* @param time 해당 값이 Redis에 유지될 시간.
* @param timeUnit 시간의 단위 (초, 분 등).
*/
public void saveAsValue(String key, Object val, Long time, TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, val, time, timeUnit);
}
final RedisTemplate<String, String> redisTemplate;
final JsonComponent jsonComponent;

/**
* 만료 시간 없이 값을 Redis에 영구적으로 저장하는 메서드.
* @param key Redis에 저장할 키.
* @param val Redis에 저장할 값.
*/
public void saveAsPermanentValue(String key, Object val) {
redisTemplate.opsForValue().set(key, val);
}
public <T> T getObjectByKey(String key, Class<T> clazz) {
ValueOperations<String, String> vop = redisTemplate.opsForValue();

/**
* Redis에 해당 키가 존재하는지 확인하는 메서드.
*
* @param key Redis에서 존재 여부를 확인할 키.
* @return 키가 존재하면 true, 없으면 false를 반환.
*/
public boolean hasKey(String key) {
return Boolean.TRUE.equals(redisTemplate.hasKey(key));
String jsonString = vop.get(key);
if (StringUtils.isNotEmpty(jsonString)) {
return jsonComponent.jsonToObject(jsonString, clazz);
} else {
return null;
}
}


/**
* Redis에서 값을 조회하는 메서드.
*
* @param key 조회할 값과 연결된 키.
* @return 주어진 키에 연결된 값, 또는 키가 존재하지 않을 경우 null.
*/
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public Object getValue(String key) {
return get(key);
}


/**
* Redis에서 해당 키를 삭제하는 메서드.
*
* @param key 삭제할 키.
* @return 키가 성공적으로 삭제되면 true, 그렇지 않으면 false.
*/
public boolean delete(String key) {
return Boolean.TRUE.equals(redisTemplate.delete(key));
public void setObjectByKey(String key, Object obj) {
ValueOperations<String, String> vop = redisTemplate.opsForValue();
vop.set(key, jsonComponent.objectToJson(obj));
redisTemplate.expire(key, 7, TimeUnit.DAYS);
}
}

0 comments on commit 205c8d8

Please sign in to comment.