4

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?

asked Dec 6, 2017 at 8:38
3
  • What was the answer to stackoverflow.com/q/48294485/6309 that you just deleted? Commented Jan 17, 2018 at 7:19
  • @VonC it turns out you should avoid setting header 'X-Artifactory-Override-Base-Url' in nginx Commented Jan 18, 2018 at 2:21
  • Great! adding that as an answer and accepting it would help others with the same problem ;) Commented Jan 18, 2018 at 5:47

1 Answer 1

2

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);
 }
}
answered Jun 16, 2020 at 10:48
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.