Say I have a User class
class User {
private Long id
private String username
private String password
}
I read a few articles/tutorials regarding storing repositories with redis in hash.
However they all have one key for the whole "table", what put into redis looks like following:
user 1 {id:1,username:'',password:''}
user 2 {id:1,username:'',password:''}
they all had id
as the hash key
in this case.
What I wanted to achieve is to use each field
as a hash key
, like below:
user:1 id 1
user:1 username ''
user:1 password ''
And after quite a lot of time searching, I found Jackson2HashMapper
could be the help. But there is no articles/documentations on how to use this mapper exactly.
Have anyone else faced similar situations?
i just use like this:
@Bean
public HashMapper<Object, byte[], byte[]> hashMapper() {
return new ObjectHashMapper();
}
@Component
public class HashMapping<T> {
@NonNull
private StringRedisTemplate stringRedisTemplate;
@NonNull
private HashMapper<Object, byte[], byte[]> hashMapper;
public void writeHash(String key, T t) {
checkNotNull(key, "hash key cannot be null");
checkNotNull(t, "hash value cannot be null");
stringRedisTemplate.execute((RedisCallback<Void>) connection -> {
Map<byte[], byte[]> mappedHash = hashMapper.toHash(t);
connection.hMSet(key.getBytes(), mappedHash);
return null;
});
}
public T loadHash(String key) {
checkNotNull(key, "hash key cannot be null");
Map<byte[], byte[]> loadedHash =
stringRedisTemplate.getConnectionFactory()
.getConnection().hGetAll(key.getBytes());
return (T) hashMapper.fromHash(loadedHash);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With