
driven-adapter.redis.redis-template.helper.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 java.time.Duration;
import org.reactivecommons.utils.ObjectMapper;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.lang.reflect.ParameterizedType;
import java.util.function.Function;
public abstract class TemplateAdapterOperations {
private final RedisTemplate template;
private final Class dataClass;
protected ObjectMapper mapper;
private final Function toEntityFn;
@SuppressWarnings("unchecked")
protected TemplateAdapterOperations(RedisConnectionFactory connectionFactory, ObjectMapper mapper, Function toEntityFn) {
this.mapper = mapper;
ParameterizedType genericSuperclass = (ParameterizedType) this.getClass().getGenericSuperclass();
this.dataClass = (Class) genericSuperclass.getActualTypeArguments()[2];
this.toEntityFn = toEntityFn;
template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setDefaultSerializer(new Jackson2JsonRedisSerializer<>(dataClass));
template.afterPropertiesSet();
}
public E save(K key, E entity) {
template.opsForValue().set(key, toValue(entity));
return entity;
}
public E save(K key, E entity, long expirationMillis) {
E result = save(key, entity);
template.expire(key, Duration.ofMillis(expirationMillis));
return result;
}
public E findById(K key) {
return toEntity(template.opsForValue().get(key));
}
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