spring-data-redis
spring-data-redis copied to clipboard
Callbacks are not parameterized fully [DATAREDIS-235]
William Hoyle opened DATAREDIS-235 and commented
Template callbacks, for example SessionCallback, only have return type parameters. This leads to some unnecessary casts. Also, the callback methods have type parameters with names that shadow the template parameter names.
Consider:
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.hash.HashMapper;
/**
* Utility for transactionally mapping objects to/from hashes.
*/
public class Hasher<T, K, V, HK, HV> {
private RedisTemplate<K, V> template;
private HashMapper<T, HK, HV> mapper;
public Hasher(RedisTemplate<K, V> template, HashMapper<T, HK, HV> mapper) {
this.template = template;
this.mapper = mapper;
}
public T get(K key) {
HashOperations<K, HK, HV> hashOps = template.opsForHash();
return mapper.fromHash(hashOps.entries(key));
}
public void put(final K key, final T value) {
//
// Clear hash and set in a transaction
//
template.execute(new SessionCallback<Void>() {
@Override
public <K, V> Void execute(RedisOperations<K, V> ops) throws DataAccessException {
ops.multi();
// Clear all values.
// Need to cast because SessionCallback is not <T, K, V>.
ops.delete((K) key); // execute<K> shadows Hasher<K>
HashOperations<K, HK, HV> hashOps = ops.opsForHash();
// Put all values.
// Need to cast again.
hashOps.putAll((K) key, mapper.toHash(value)); // cast again
ops.exec();
return null;
}
});
}
}
1 votes, 2 watchers
Markus Heiden commented
The type parameters K and V should be at type level, not a method level. Otherwise it is not possible to use SessionCallback as a lambda. RedisTemplate#execute should look like: public <T> T execute(SessionCallback<K, V, T> session) { ... } This way type safety is ensured.
No one assigned
2023.....