
driven-adapter.redis-reactive.redis-template.helper.reactive-template-adapter-operations.mustache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of scaffold-clean-architecture Show documentation
Show all versions of scaffold-clean-architecture Show documentation
Gradle plugin to create a clean application in Java that already works, It follows our best practices!
package {{package}}.redis.template.helper;
import org.reactivecommons.utils.ObjectMapper;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import reactor.core.publisher.Mono;
import java.lang.reflect.ParameterizedType;
import java.time.Duration;
import java.util.function.Function;
public abstract class ReactiveTemplateAdapterOperations {
private final ReactiveRedisTemplate template;
private final Class dataClass;
protected ObjectMapper mapper;
private final Function toEntityFn;
@SuppressWarnings("unchecked")
protected ReactiveTemplateAdapterOperations(ReactiveRedisConnectionFactory connectionFactory, ObjectMapper mapper, Function toEntityFn) {
this.mapper = mapper;
ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
this.dataClass = (Class) genericSuperclass.getActualTypeArguments()[2];
this.toEntityFn = toEntityFn;
RedisSerializationContext serializationContext =
RedisSerializationContext.newSerializationContext(new Jackson2JsonRedisSerializer<>(dataClass))
.build();
template = new ReactiveRedisTemplate<>(connectionFactory, serializationContext);
}
public Mono save(K key, E entity) {
return Mono.just(entity)
.map(this::toValue)
.flatMap(value -> template.opsForValue().set(key, value))
.thenReturn(entity);
}
public Mono save(K key, E entity, long expirationMillis) {
return save(key, entity)
.flatMap(v -> template.expire(key, Duration.ofMillis(expirationMillis)).thenReturn(v));
}
public Mono findById(K key) {
return template.opsForValue().get(key)
.map(this::toEntity);
}
protected V toValue(E entity) {
return mapper.map(entity, dataClass);
}
protected E toEntity(V data) {
return data != null ? toEntityFn.apply(data) : null;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy