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?
-
What was the answer to stackoverflow.com/q/48294485/6309 that you just deleted?VonC– VonC2018年01月17日 07:19:20 +00:00Commented Jan 17, 2018 at 7:19
-
@VonC it turns out you should avoid setting header 'X-Artifactory-Override-Base-Url' in nginxQiaosen Huang– Qiaosen Huang2018年01月18日 02:21:26 +00:00Commented Jan 18, 2018 at 2:21
-
Great! adding that as an answer and accepting it would help others with the same problem ;)VonC– VonC2018年01月18日 05:47:47 +00:00Commented Jan 18, 2018 at 5:47
1 Answer 1
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);
}
}
Comments
Explore related questions
See similar questions with these tags.