Files
mtusi2026lab4/src/main/java/com/example/mtusi_messenger/cache/UserCache.java
T

84 lines
2.8 KiB
Java

package com.example.mtusi_messenger.cache;
import com.example.mtusi_messenger.model.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
@Component
public class UserCache {
private static final Logger log = LoggerFactory.getLogger(UserCache.class);
private static final String KEY_PREFIX = "messenger:user:";
private final StringRedisTemplate redis;
private final ObjectMapper mapper;
private final Duration ttl;
public UserCache(
StringRedisTemplate redis,
ObjectMapper mapper,
@Value("${messenger.cache.user-ttl-seconds:300}") long ttlSeconds
) {
if (ttlSeconds <= 0) {
throw new IllegalArgumentException("User cache TTL must be positive");
}
this.redis = redis;
this.mapper = mapper;
this.ttl = Duration.ofSeconds(ttlSeconds);
}
public Optional<User> find(UUID userId) {
try {
String value = redis.opsForValue().get(key(userId));
if (value == null) {
return Optional.empty();
}
User cachedUser = mapper.readValue(value, User.class);
if (cachedUser == null) {
log.warn("Ignoring null Redis user cache entry for {}", userId);
evict(userId);
return Optional.empty();
}
return Optional.of(cachedUser);
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; using PostgreSQL fallback");
return Optional.empty();
} catch (JsonProcessingException e) {
log.warn("Ignoring malformed Redis user cache entry for {}", userId);
evict(userId);
return Optional.empty();
}
}
public void put(User user) {
try {
redis.opsForValue().set(key(user.id()), mapper.writeValueAsString(user), ttl);
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; user was not cached");
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize user cache entry", e);
}
}
public void evict(UUID userId) {
try {
redis.delete(key(userId));
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; cache eviction was skipped");
}
}
private String key(UUID userId) {
return KEY_PREFIX + userId;
}
}