Перенос из 3 лабы
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package org.example.service;
|
||||
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class CacheService {
|
||||
|
||||
private static final String PREFIX = "session:";
|
||||
private final StringRedisTemplate redis;
|
||||
|
||||
public void put(String token, UUID userId, Instant expiresAt){
|
||||
long ttlSec = Duration.between(Instant.now(), expiresAt).getSeconds();
|
||||
if (ttlSec <= 0){
|
||||
return;
|
||||
}
|
||||
try {
|
||||
redis.opsForValue().set(
|
||||
PREFIX + token,
|
||||
userId.toString(),
|
||||
ttlSec,
|
||||
TimeUnit.SECONDS
|
||||
);
|
||||
} catch (Exception e){
|
||||
log.warn("Сессия не попала в Redis");
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<UUID> get(String token){
|
||||
try {
|
||||
String v = redis.opsForValue().get(PREFIX + token);
|
||||
if (v == null || v.isBlank()){
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(UUID.fromString(v));
|
||||
} catch (Exception e){
|
||||
log.warn("Сессии нет в Redis");
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public void deleteSession(String token){
|
||||
try {
|
||||
redis.delete(PREFIX + token);
|
||||
} catch (Exception e){
|
||||
log.warn("Сессия не удалена в Redis");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user