ASP.NET core Redis

Scenario:

Create a Sign on service to allow creation of users in our app. The web App calls this service to get all users. Cache the data into Redis and serve the next request from cache till it expires.

Solution:

You need the Redis server and then you need to get the .NET client API (like StackExchange.Redis).

  1. Install:
    1. Download from https://github.com/MicrosoftArchive/redis/releases
    2. Install as windows service using Redis-x64-3.0.504.msi. set port to 6379
    3. It is avialble on "127.0.0.1" and port "6379".

  2. Install Nuget package - StackExchange.Redis

  3. Add ICache.cs

  4.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    namespace Web.Services
    {
        public interface ICache<TValue>
        {
            bool TrySet(string key, TValue value);
    
            bool TryGet(string key, out TValue value);
    
            void Remove(string key);
    
            void RemoveAll();
        }
    }
    

  5. Add ICacheService.cs

  6. 1
    2
    3
    4
    5
    6
    7
    namespace Web.Services
    {
        public interface ICacheService
        {
            ICache<TValue> GetCache<TValue>(string name);
        }
    }
    

  7. Add RedisCacheService.cs

  8.   
     
     1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    using GrpcServer;
    using Microsoft.Extensions.Caching.Memory;
    using Microsoft.Extensions.Primitives;
    using StackExchange.Redis;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Threading;
    
    namespace Web.Services
    {
        //Redis cache
        public class RedisCacheService : ICacheService
        {
            private static IConnectionMultiplexer _connectionMultiplexer;
            private static readonly Dictionary<string, object> _repo;
            private readonly ReaderWriterLockSlim Lock = new ReaderWriterLockSlim();
            public RedisCacheService(IConnectionMultiplexer connectionMultiplexer)
            {
                _connectionMultiplexer = connectionMultiplexer;
            }
    
            static RedisCacheService()
            {
                //create cache repo
                _repo = new Dictionary<string, object>();
            }
            public ICache<TValue> GetCache<TValue>(string name)
            {
                object cache = null;
    
                Lock.EnterUpgradeableReadLock();
                try
                {
                    Lock.EnterWriteLock();
                    if (!_repo.TryGetValue(name, out cache))
                    {
                        cache = new RedisCache<TValue>(_connectionMultiplexer);
                        _repo[name] = cache;
                    }
                }
                finally
                {
                    Lock.ExitWriteLock();
                    Lock.ExitUpgradeableReadLock();
                }
    
                return (ICache<TValue>)cache;
            }
        }
    
        public class RedisCache<TValue> : ICache<TValue>
        {
            private static IDatabase _cache;
            private static IConnectionMultiplexer _connectionMultiplexer;
    
            private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
    
            static RedisCache()
            {
            }
    
            public RedisCache(IConnectionMultiplexer connectionMultiplexer)
            {
                _connectionMultiplexer = connectionMultiplexer;
            }
    
            public void Remove(string key)
            {
                _lock.EnterWriteLock();
                try
                {
                    _cache.KeyDelete(key);
                }
                finally
                {
                    _lock.ExitWriteLock();
                }
            }
    
            public bool TryGet(string key, out TValue value)
            {
                _lock.EnterUpgradeableReadLock();
                try
                {
                    var result = _connectionMultiplexer.GetDatabase().StringGet(key);
                    
                    if (result.HasValue)
                       {
                        value = Deserialize<TValue>(result);
                        return true;
                    }
                }
                catch (Exception e)
                {
                    value = default(TValue);
                }
                finally
                {
                    _lock.ExitUpgradeableReadLock();
                }
                value = default(TValue);
                return false;
            }
    
            public bool TrySet(string key, TValue value)
            {
                _lock.EnterWriteLock();
    
                var result = _connectionMultiplexer.GetDatabase().StringGet(key);
    
                if (!result.HasValue)
                {
                    try
                    {
                        _connectionMultiplexer.GetDatabase().StringSet(key, Serialize(value), TimeSpan.FromSeconds(10));
                        return true;
                    }
                    catch (Exception e)
                    {
                        return false;
                    }
                    finally
                    {
                        _lock.ExitWriteLock();
                    }
                }
    
                return true;
            }
    
            public void RemoveAll()
            {
                _lock.EnterWriteLock();
                try
                {
                    _connectionMultiplexer.GetServer(ConfigurationManager.AppSetting["redis:server"]).FlushAllDatabases();
                }
                catch (Exception)
                {
                }
                finally
                {
                    _lock.ExitWriteLock();
                }
            }
    
            static byte[] Serialize(object o)
            {
                if (o == null)
                {
                    return null;
                }
    
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    binaryFormatter.Serialize(memoryStream, o);
                    byte[] objectDataAsStream = memoryStream.ToArray();
                    return objectDataAsStream;
                }
            }
    
            static TValue Deserialize<TValue>(byte[] stream)
            {
                if (stream == null)
                {
                    return default(TValue);
                }
    
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                using (MemoryStream memoryStream = new MemoryStream(stream))
                {
                    TValue result = (TValue)binaryFormatter.Deserialize(memoryStream);
                    return result;
                }
            }
        }
    
    

  9. In Startup.cs

  10. 1
    2
    3
    4
    5
    6
    7
                services.AddSingleton<ICacheService, RedisCacheService>();
                services.AddSingleton<ICache<object>, RedisCache<object>>();
    
                var options = ConfigurationOptions.Parse(ConfigurationManager.AppSetting["redis:server"]);
                options.AllowAdmin = true;
    
                services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect(options));
    
  11. Add HomeController.cs

  12.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
     public class HomeController : Controller
        {
    private ILogger _logger;
    private readonly ICache<List<string>> _userCache;
     public HomeController(ILoggerFactory loggerFactory, SignOn.SignOnClient signOnClient, ICacheService cacheService, IMemoryCache memoryCache)
            {
    _logger = loggerFactory.CreateLogger<InMemoryCacheService>();
                _userCache = cacheService.GetCache<List<string>>("cache_users");
                _cache = memoryCache;
    }
    private async Task<Tuple<bool, List<string>>> GetUsers()
            {
                var userlist = new List<string>();
                string name = string.Empty;
    
                var cachekey = CacheKeys.Users;
    
                _usersLock.EnterReadLock();
    
                try
                {
                    if (_userCache.TryGet(cachekey, out userlist))
                    {
                        return new Tuple<bool, List<string>>(true, userlist);
                    }
    
                    if (_userCache.TryGet(CacheKeys.CallbackMessage, out var message))
                    {
                        _logger.LogDebug(message.First());
                    }
                }
                finally
                {
                    _usersLock.ExitReadLock();
                }
    
                try
                {
                    _usersLock.EnterWriteLock();
    
                    using (var call = _signOnClient.GetAllUsers(new UserRequest()))
                    {
                        userlist = new List<string>();
                        while (await call.ResponseStream.MoveNext())
                        {
                            var user = call.ResponseStream.Current;
                            userlist.Add(user.Name);
                        }
                    }
    
                    if (_userCache.TrySet(cachekey,userlist))
                    {
                        return new Tuple<bool, List<string>>(true, userlist);
                    }
    
                    return new Tuple<bool, List<string>>(false, null);
                }
                catch (Exception)
                {
                    return new Tuple<bool, List<string>>(false, null);
                }
                finally
                {
                    _usersLock.ExitWriteLock();
                }
            }
     try
                {
                    if (!all)
                    {
                        _userCache.Remove(CacheKeys.Users);
                    }
                    else
                    {
                        _userCache.RemoveAll();
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
    
                return View();
            }
        }
    

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...