/*
* Copyright 2019, Pearson Education, Learning Technology Group
*
* RedisCacheServiceImpl.java
*/
package com.pearson.ltg.rbs.ltitoolgateway.redis.service;
import java.time.Duration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.stereotype.Service;
import com.pearson.ltg.rbs.ltitoolgateway.model.PlatformConfiguration;
import reactor.core.publisher.Mono;
@Service
public class RedisCacheServiceImpl implements IRedisCacheService {
@Value("${redis.expiry.time : 3600}")
protected long expiryTime;
@Autowired
ReactiveRedisTemplate<String, Object> redisTemplate;
public Mono<PlatformConfiguration> getPlatformConfigurationFromCache(String cacheKey) {
Mono<Object> configMono = redisTemplate.opsForValue().get(cacheKey);
return configMono.map(config -> {
return (PlatformConfiguration)config;
});
}
public void savePlatformConfigurationInCache(String cacheKey, Mono<PlatformConfiguration> platformConfiguration) {
redisTemplate.opsForValue().set(cacheKey, platformConfiguration);
setExpiryTime(cacheKey);
}
public Mono<String> getPlatformIdFromCache(String cacheKey) {
return redisTemplate.opsForValue().get(cacheKey).flatMap(cache -> {
return Mono.just((String)cache);
});
}
public void savePlatformIdInCache(String cacheKey, String platformId) {
redisTemplate.opsForValue().set(cacheKey, platformId);
setExpiryTime(cacheKey);
}
@Override
public void flushRedisCache() {
ReactiveRedisConnectionFactory redisConnectionFactory = redisTemplate.getConnectionFactory();
if (null != redisConnectionFactory) {
redisConnectionFactory.getReactiveConnection().serverCommands().flushAll();
}
}
@Override
public void deleteKey(String cacheKey) {
if (StringUtils.isNotEmpty(cacheKey)) {
redisTemplate.delete(cacheKey);
}
}
private void setExpiryTime(String cacheKey) {
redisTemplate.expire(cacheKey, Duration.ofSeconds(expiryTime));
}
}