how can I access to a hashed key stored by spring

2019-06-06 08:04发布

问题:

I have this problem.

There is a spring session stored in redis,saved this way

HMSET spring:session:sessions:33fdd1b6-b496-4b33-9f7d-df96679d32fe creationTime 1404360000000 \
    maxInactiveInterval 1800 \
    lastAccessedTime 1404360000000 \
    sessionAttr:attrName someAttrValue \
    sessionAttr2:attrName someAttrValue2

As far as I understand is a hashed set.

I can access it via redis-cli with HMGET that as far as I understand is to get values of hashed keys.

Works great.

Now on spring, I want to access it via Redis Template (org.springframework.data.redis.core).

So, I did this

@Autowired RedisOperationsSessionRepository redisOperationsSessionRepository;

@Autowired RedisTemplate redisTemplate;

and tried...

stringRedisTemplate.opsForValue().get(loggedSessionId);

redisTemplate.opsForHash().get("mykey", WHAT GOES HERE?)
redisOperationsSessionRepository.sessionRedisOperations.opsForHash().get(mykey", OR HERE?)

so far I cannot access it to the information, any idea what hash I have to define? there is no info how spring gets it ...

Thanks.

EDIT:

What I basically want to do is

COPY this

and save it in other redis using another template...

as you can see, it has not the value serialized in right way, could be a problem if I just copy and "paste" the objects using opsForHash or will I save corrupted data?

回答1:

Quote from https://redis.io/topics/data-types

Redis Hashes are maps between string fields and string values ...

So

redisTemplate.opsForHash().get("mykey", "myKeyHash")

Will return value of the field myKeyHash stored in key mykey.

For your examle your fileds would be creationTime, maxInactiveInterval, lastAccessedTime and attributes.

By the way there is a more convinient method:

redisTemplate.opsForHash().entries("mykey")

that returns map of all fileds contained in that hash with their values.

EDIT

Since Spring uses JdkSerializationRedisSerializer for valules and StringRedisSerializer for keys/hash keys, you must configure your RedistTemplate as follows to be able to read data correctly:

RedisTemplate<String, Object> template = new RedisTemplate<>(); 
RedisSerializer stringSerializer = new StringRedisSerializer();
template.setConnectionFactory(...); 
template.setKeySerializer(stringSerializer); 
template.setHashKeySerializer(stringSerializer);