Using simple SET with StackExchangeRedis?

Viewed 970

I'm using .Net core with StackExchangeRedis:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddStackExchangeRedisCache(options =>
           {
               options.Configuration = "127.0.0.1:6379";
           });
        services.AddControllers();

    }

Later I inject the service and testing it via set/get :

private readonly IDistributedCache _cache;

        public MyRedisController(IDistributedCache cache)
        {
            _cache = cache;
        }

        [HttpGet]
        public async Task<string> Get()
        { 
             _cache.SetString("dd", "5");
            var a = await _cache.GetStringAsync("dd"); //5
            return a;


        }

The problem is that when I try to get the value in redis-cli, I see :

127.0.0.1:6379> get "dd"
(error) WRONGTYPE Operation against a key holding the wrong kind of value

After investigating, I see that it's stored as a hash:

enter image description here

Question:

How can I use StackExchangeRedis to store simple string types without the hash type ? I want a simple string. (get/set)

ps
I know I can get the value via: hget "dd" data. But I'm after storing simple string type.

1 Answers

Just to be clear: none of the code shown in the question is (directly) touching StackExchange.Redis; AddStackExchangeRedisCache is an ASP.NET layer wrapper by Microsoft, and is not part of StackExchange.Redis - it looks like it does other things to encapsulate additional features such as absolute/sliding expiration, although frankly (as observations):

  1. if -1 means "not set", they could have just not stored a hash field
  2. absolute expiration is supported directly in redis via EXPIRE

I'm happy to add an answer, but it will only be in terms of StackExchange.Redis:

// note: the multiplexer is disposable, but you usually keep this around
//  and reuse it between lots of operations - don't Connect each time
var muxer = ConnectionMultiplexer.Connect("127.0.0.1:6379");

// actually do things
var db = muxer.GetDatabase();
db.StringSet("dd", 5);
var value = db.StringGet("dd");
Console.WriteLine((int)value);

If you want to see what AddStackExchangeRedisCache is doing behind the scenes, you can use redis-cli MONITOR to see what commands it issues in your original code.

Related