Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis Cache in ASP.NET Core

I am new to Redis and using VS 2015 and the ASP.NET Core app (v 1.0), I installed the nugget package:

Install-Package StackExchange.Redis

However I am not able to inject and configure it into my services, there is no RedisCache or "AddDistributedRedisCache" method.

How can I inject and use it?

like image 206
Hussein Salman Avatar asked Nov 01 '16 20:11

Hussein Salman


People also ask

What is Redis cache in ASP.NET Core?

Redis is an open source in-memory data store, which is often used as a distributed cache. You can configure an Azure Redis Cache for an Azure-hosted ASP.NET Core app, and use an Azure Redis Cache for local development. An app configures the cache implementation using a RedisCache instance (AddStackExchangeRedisCache).

What is Redis cache C#?

What is Redis Cache. Redis is an open source (BSD licensed), in-memory data structure store used as a database, cache, message broker, and streaming engine. Redis provides data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes, and streams.


2 Answers

01.Download latest redis from download ,install and start the redis service from services.msc

02.Add two library in project.json

"Microsoft.Extensions.Caching.Redis.Core": "1.0.3",
"Microsoft.AspNetCore.Session": "1.1.0",

03.Add you dependency injection in

public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddMvc();
        //For Redis
        services.AddSession();
        services.AddDistributedRedisCache(options =>
        {
            options.InstanceName = "Sample";
            options.Configuration = "localhost";
        });
  } 
  1. and in Configure method add top of app.UseMvc line

    app.UseSession();

to use redis in session storage in asp.net core .Now you can use like this in HomeController.cs

public class HomeController : Controller
{
    private readonly IDistributedCache _distributedCache;
    public HomeController(IDistributedCache distributedCache)
    {
        _distributedCache = distributedCache;
    }
    //Use version Redis 3.22
    //http://stackoverflow.com/questions/35614066/redissessionstateprovider-err-unknown-command-eval
    public IActionResult Index()
    {
        _distributedCache.SetString("helloFromRedis", "world");
        var valueFromRedis = _distributedCache.GetString("helloFromRedis");
        return View();
    }
 }
like image 115
syed mhamudul hasan akash Avatar answered Sep 28 '22 07:09

syed mhamudul hasan akash


I used the following solution and got the answer.

1.Download Redis-x64-3.0.504.msi and install it (link)

2.Install Microsoft.Extensions.Caching.StackExchangeRedis from Nuget Packge Manager

3.Inside the Startup.cs class ,In the ConfigureServices method, add this command:

 services.AddStackExchangeRedisCache(options => options.Configuration = "localhost:6379");
  1. inject IDistributedCache to the controller:

     private readonly IDistributedCache _distributedCache;
    
     public WeatherForecastController( IDistributedCache distributedCache)
     {
         _distributedCache = distributedCache;
     }
    

5.In the end:

   [HttpGet]
    public async Task<List<string>> GetStringItems()
    {
        string cacheKey = "redisCacheKey";
        string serializedStringItems;
        List<string> stringItemsList;

        var encodedStringItems = await _distributedCache.GetAsync(cacheKey);
        if (encodedStringItems != null)
        {
            serializedStringItems = Encoding.UTF8.GetString(encodedStringItems);
            stringItemsList = JsonConvert.DeserializeObject<List<string>>(serializedStringItems);
        }
        else
        {
            stringItemsList = new List<string>() { "John wick", "La La Land", "It" };
            serializedStringItems = JsonConvert.SerializeObject(stringItemsList);
            encodedStringItems = Encoding.UTF8.GetBytes(serializedStringItems);
            var options = new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(1))
                .SetAbsoluteExpiration(TimeSpan.FromHours(6));
            await _distributedCache.SetAsync(cacheKey, encodedStringItems, options);

        }
        return stringItemsList;
    }

Good luck!!!

like image 22
Milad Safari Avatar answered Sep 28 '22 09:09

Milad Safari