I am trying to save hash value in Mojo::Redis2. The sample hash value is given below.
'user' => {
'manage-detail' => {
'46' => 'edit',
'45' => 'list',
'44' => 'create',
'48' => 'delete',
'47' => 'search'
},
'manage-procedure' => {
'27' => 'search',
'25' => 'list',
'24' => 'create',
'26' => 'edit'
}
}
I am saving and reading from redis using the code below.
$self->app->redis->hset('test', %HoH);
my %res = $self->app->redis->hget("test",'user');
But it is not working. When reading the hash value is empty.
You misunderstand what HSET
does in Redis. It's not for saving a whole Perl data structure. It's for saving a single value under a specific key inside the hash data structure that Redis offers. That's different from a normal key/value store operation insofar that you can then use other Redis hash related operations on it.
It seems what you want to do is save a complete Perl data structure for later use, without operating on the data inside it from within Redis.
You can use a regular SET
operation for that, but you need to serialise your Perl data structure for that. Essentially that means to turn the memory that your Perl program uses to store these values into character data that other programs can understand.
Common tools for serialising and deserialising data in Perl are Storable or Sereal. The latter is more powerful, but probably only makes sense on large data structures.
If your data only contains text, any JSON implementation would also work, which would give you the added benefit of programs in other languages being able to read and write this data, increasing interoperability, at the cost of needing more memory.
Giving a full implementation of this would be outside of the scope of this answer, but effectively what you need to do is this:
# to store
$self->app->redis->set('namespace:key', serealise(\%HoH));
# to retrieve
my $hashref_of_hashes = deserialise($self->app->redis->get('namespace:key'));
Where serealise()
and deserealise()
are synonymous for a freezing and thawing (turning into a string or back) mechanism.
You might also want to take a look at the cache interface CHI.