Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻ refactor(IDistributedCache): Optimize connections under Isolation and Attempt to reconnect #740

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

namespace Masa.BuildingBlocks.Caching;

internal class DistributedCacheClientCache
Copy link
Contributor

@capdiem capdiem Oct 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

DistributedCacheClientCache的后缀Cache是OK的吗?你这是个工厂吧,改成ClientFactory?

{
public static ConcurrentDictionary<string, IManualDistributedCacheClient> CacheClients { get; set; } = new();

public IManualDistributedCacheClient GetCacheClient(IServiceProvider serviceProvider)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IHttpClientFactory用的时CreateClient,要对其它吗?

{
var multiEnvironmentContext = serviceProvider.GetRequiredService<IMultiEnvironmentContext>();
var environment = multiEnvironmentContext.CurrentEnvironment;

return CacheClients.GetOrAdd(environment, env =>
{
var cacheClient = serviceProvider.GetRequiredService<ScopedService<IManualDistributedCacheClient>>().Service;
return cacheClient;
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ public static void TryAddDistributedCache(
services.TryAddTransient<IManualDistributedCacheClient>(serviceProvider =>
{
var cacheClient = serviceProvider.EnableIsolation() ?
serviceProvider.GetRequiredService<ScopedService<IManualDistributedCacheClient>>().Service :
serviceProvider.GetRequiredService<DistributedCacheClientCache>().GetCacheClient(serviceProvider) :
serviceProvider.GetRequiredService<SingletonService<IManualDistributedCacheClient>>().Service;

return new DefaultDistributedCacheClient(cacheClient);
});
services.TryAddTransient<IDistributedCacheClient>(serviceProvider
Expand Down Expand Up @@ -65,6 +66,8 @@ private static void AddTypeAlias(

private static void AddCaching(this IServiceCollection services)
{
services.TryAddSingleton<DistributedCacheClientCache>();

services.TryAddSingleton<SingletonService<IManualDistributedCacheClient>>(serviceProvider =>
new SingletonService<IManualDistributedCacheClient>(serviceProvider.GetRequiredService<IDistributedCacheClientFactory>()
.Create()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,29 @@ public abstract class RedisCacheClientBase : DistributedCacheClientBase
{
protected readonly string? InstanceId;
protected static readonly Guid UniquelyIdentifies = Guid.NewGuid();
protected readonly ISubscriber Subscriber;
protected ISubscriber Subscriber;

protected IDatabase Db
{
get
{
if (_connection.IsConnected || _connection.IsConnecting)
return _connection.GetDatabase();

throw new NotSupportedException("Redis service has been disconnected, please wait for reconnection and try again");
return EnsureDbConnection();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EnsureABC方法一般是返回void,里面可以抛异常。大概是这样:

EnsureABC();

return _connect.GetDatabase();

}
}

private readonly IConnectionMultiplexer _connection;
private IConnectionMultiplexer _connection;
protected readonly JsonSerializerOptions GlobalJsonSerializerOptions;
private readonly CacheEntryOptions _globalCacheEntryOptions;
private readonly CacheOptions _globalCacheOptions;

private readonly RedisConfigurationOptions _redisConfigurationOptions;

protected RedisCacheClientBase(
RedisConfigurationOptions redisConfigurationOptions,
JsonSerializerOptions? jsonSerializerOptions)
: this(redisConfigurationOptions.GlobalCacheOptions, redisConfigurationOptions, jsonSerializerOptions)
{
_redisConfigurationOptions = redisConfigurationOptions;
var redisConfiguration = redisConfigurationOptions.GetAvailableRedisOptions();
_connection = ConnectionMultiplexer.Connect(redisConfiguration);
Subscriber = _connection.GetSubscriber();
Expand All @@ -51,6 +51,28 @@ private RedisCacheClientBase(
GlobalJsonSerializerOptions = jsonSerializerOptions ?? new JsonSerializerOptions().EnableDynamicTypes();
}

protected IDatabase EnsureDbConnection()
{
if (_connection.IsConnected || _connection.IsConnecting)
{
return _connection.GetDatabase();
}

// Attempt to reconnect
var redisConfiguration = _redisConfigurationOptions.GetAvailableRedisOptions();
_connection = ConnectionMultiplexer.Connect(redisConfiguration);
Subscriber = _connection.GetSubscriber();

if (_connection.IsConnected || _connection.IsConnecting)
{
return _connection.GetDatabase();
}
else
{
throw new NotSupportedException("Unable to reconnect to Redis, please check the connection settings and try again.");
}
}

protected T? ConvertToValue<T>(RedisValue value, out bool isExist)
{
if (value is { HasValue: true, IsNullOrEmpty: false })
Expand Down
Loading