且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Azure上托管的ASP.NET Core App中Redis连接中的错误

更新时间:2023-02-15 08:24:00

每次依赖注入调用实例化RedisService类时,您的代码最终都会向lazyConnection分配新的Lazy<ConnectionMultiplexer>,从而导致新的连接以及连接泄漏,因为您没有在旧的lazyConnection上调用Close()或Dispose().

Each time your dependency injection calls instantiates the RedisService class, your code ends up assigning a new Lazy<ConnectionMultiplexer> to lazyConnection, thus resulting in a new connection as well as a connection leak as you are not calling Close() or Dispose() on the old lazyConnection.

尝试像这样更改代码:

在Startup.cs中:

In Startup.cs:

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            .........<whatever you have here>
            services.AddSingleton<RedisService>();
            services.Configure<ApplicationSettings>(options => Configuration.GetSection("ApplicationSettings").Bind(options));
        }

RedisService.cs

RedisService.cs

public class RedisService
{
    private readonly ApplicationSettings _settings;
    private static Lazy<ConnectionMultiplexer> lazyConnection;
    static object connectLock = new object();

    public RedisService(IOptions<ApplicationSettings> settings)
    {
        _settings = settings.Value;
        if (lazyConnection == null)
        {
            lock (connectLock)
            {
                if (lazyConnection == null)
                {
                    lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
                    {
                        return ConnectionMultiplexer.Connect(_settings.RedisConnection);
                    });
                }
            }
        }
    }

    public static ConnectionMultiplexer Connection
    {
        get
        {
            return lazyConnection.Value;
        }
    }
}

ApplicationSettings.cs

ApplicationSettings.cs

public class ApplicationSettings
    {
        public string RedisConnection { get; set; }
    }

appsettings.json

appsettings.json

{
    "Logging": {
        "IncludeScopes": false,
        "LogLevel": {
            "Default": "Debug",
            "System": "Information",
            "Microsoft": "Information"
        }
    },
    "ApplicationSettings": {
        "RedisConnection": "yourcachename.redis.cache.windows.net:6380,password=yourpassword,ssl=True,abortConnect=False,syncTimeout=4000"
    }
}

HomeController.cs

HomeController.cs

public class HomeController : Controller
    {
        private RedisService redisService;
        private ConnectionMultiplexer connectionMultiplexer;
        public HomeController(IOptions<ApplicationSettings> settings)
        {
            redisService = new RedisService(settings);
            connectionMultiplexer = RedisService.Connection;
        }
        public IActionResult Index()
        {
            AddToCache("foo1", "bar").GetAwaiter().GetResult();

            return View();
        }

        private async Task<string> GetFromCache(string key)
        {
            if (connectionMultiplexer.IsConnected)
            {
                var cache = connectionMultiplexer.GetDatabase();

                return await cache.StringGetAsync(key);
            }
            else
            {
                return null;
            }
        }

        private async Task DeleteFromCache(string subdomain)
        {
            if (connectionMultiplexer.IsConnected)
            {
                var cache = connectionMultiplexer.GetDatabase();
                await cache.KeyDeleteAsync(subdomain).ConfigureAwait(false);
            }
        }

        private async Task AddToCache(string key, string serializedData)
        {
            var GetMessagesCacheExpiryMinutes = 5;
            var GetProfileCacheExpiryHours = 1;
            if (connectionMultiplexer.IsConnected)
            {
                var cache = connectionMultiplexer.GetDatabase();

                TimeSpan expiresIn;
                // Search Cache
                if (key.Contains("-"))
                {
                    expiresIn = new TimeSpan(0, GetMessagesCacheExpiryMinutes, 0);
                }
                // User info cache
                else
                {
                    expiresIn = new TimeSpan(GetProfileCacheExpiryHours, 0, 0);
                }
                await cache.StringSetAsync(key, serializedData, expiresIn).ConfigureAwait(false);

            }
        }