重新整理 .net core 實踐篇————緩存相關[四十二]


前言

簡單整理一下緩存。

正文

緩存是什么?

  1. 緩存是計算結果的"臨時"存儲和重復使用

  2. 緩存本質是用空間換取時間

緩存的場景:

  1. 計算結果,如:反射對象緩存

  2. 請求結果,如:DNS 緩存

  3. 臨時共享數據,如:會話存儲

  4. 熱點訪問內容頁,如:商品詳情

  5. 熱點變更邏輯數據,如:秒殺的庫存數

緩存的策略:

  1. 越接近最終的數據結構,效果比較好

  2. 緩存命中率越高越好,命中率低意味着空間的浪費。

緩存的位置:

  1. 瀏覽器中

  2. 反向代理服務器中(nginx)

  3. 應用進程內存中

  4. 分布式存儲系統中(redis)

緩存實現的要點:

  1. 存儲key生成策略,表示緩存數據的范圍、業務含義

  2. 緩存失效的策略,如:過期時間機制、主動刷新機制

  3. 緩存的更新策略,表示更新緩存數據的時機

緩存的幾個問題:

  1. 緩存失效,導致數據不一致。是指緩存的數據與我們數據庫里面的數據不一致的情況。

  2. 緩存穿透,查詢無數據時,導致緩存不生效,查詢都落到了數據庫上

  3. 緩存擊穿,緩存失效瞬間,大量請求訪問到數據庫

  4. 緩存雪崩,大量緩存在同一時間失效,導致數據庫壓力大

上面這些哪里看的最多呢?redis的面經的,我現在都沒有想明白這些和reids有什么關系,這些本來就是緩存問題,只不過redis當緩存的時候,自然就遇到了緩存的問題了。

下面來簡單介紹一下這幾個問題。

第一點,緩存失效,就是和我們數據庫里面的數據不一致,這個就是代碼業務問題了,業務沒有做好。

第二個,緩存穿透,因為一些數據不存在,然后緩存中自然是沒有的,然后就會一直訪問數據庫,然后數據庫壓力就大。

這個很有可能是別人的攻擊。那么防護措施可以這么干,當數據庫里面沒有的時候,可以在緩存中設置key:null,依然加入緩存中取,這樣訪問的就是緩存了。

第三點,緩存擊穿,指的是大量用戶訪問同一個緩存,當緩存失效的時候,每個請求都會去訪問數據庫。

那么這個時候,比較簡單的方式就是加鎖。

// xx查詢為空
if(xx==null)
{
   lock(obj)
   {
      // 再查一次
       ....
      //如果沒有去數據庫里面取數據,加入緩存中
      if(xx=null)
      {
       // 進行數據庫查詢,加入緩存,給xx賦值
       ....
      }
   }
}

這種是大量用戶訪問同一個緩存的情況,當然也可以設置緩存不過期,但是不能保證緩存不被清理吧。就是說緩存不過期是在理想情況,但是怎么沒的,就屬於突發情況了。

第四點,緩存雪崩。就是比如說有1w個用戶現在來請求了,然后艱難的給他們都加上了緩存,然后就把他們的緩存時間設置為半個小時,然后半個小時后,這一萬個請求又來了,但是緩存沒了,這時候又要艱難的從數據庫里面讀取。

那么這種情況怎么解決呢? 最簡單的就是不要設置設置固定的緩存失效數字,可以隨機一個數字。但是如果用戶體過大,同樣面臨着某一個時間點大量用戶失效的情況。那么同樣可以,當拿到用戶緩存的時候,如果時間快到期了,然后給他續時間。

那么就來舉例子。

需要用到的組件如下:

  1. responseCache 中間件

  2. Miscrosoft.Extensions.Caching.Memory.IMemoryCache MemoryCache

  3. Miscrosoft.Extensions.Caching.Distributed.IDistributedCache 分布式cache

  4. EasyCaching 開源chache組件

內存緩存和分布式緩存的區別

  1. 內存緩存可以存儲任意的對象

  2. 分布式緩存的對象需要支持序列化

  3. 分布式緩存遠程請求可能失敗(網絡問題,或者遠程服務緩存進程崩潰等),內存緩存不會(內存緩存沒有網絡問題)

下面是例子:

需要安裝的包:

  1. EasyCaching.Redis

  2. microsoft.extensions.Caching.StackExchangeRedis

先來介紹一下內存緩存,內存緩存是我們框架自帶的。

services.AddMemoryCache();

這樣就是就開啟了我們的內存緩存。

簡答看下AddMemoryCache。

public static IServiceCollection AddMemoryCache(this IServiceCollection services)
{
	if (services == null)
	{
		throw new ArgumentNullException(nameof(services));
	}

	services.AddOptions();
	services.TryAdd(ServiceDescriptor.Singleton<IMemoryCache, MemoryCache>());

	return services;
}

實際上注冊了IMemoryCache,為MemoryCache。這個MemoryCache就不看了,就是一些key value 之類緩存的方法。

那么來看一下services.AddResponseCaching();,啟動Response cache 服務。

/// <summary>
/// Add response caching services.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> for adding services.</param>
/// <returns></returns>
public static IServiceCollection AddResponseCaching(this IServiceCollection services)
{
	if (services == null)
	{
		throw new ArgumentNullException(nameof(services));
	}

	services.TryAddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();

	return services;
}

這個是我們請求結果的緩存,那么還得寫入中間件。

services.AddResponseCaching();

那么簡單看一下AddResponseCaching這個中間件。

public static IApplicationBuilder UseResponseCaching(this IApplicationBuilder app)
{
	if (app == null)
	{
		throw new ArgumentNullException(nameof(app));
	}

	return app.UseMiddleware<ResponseCachingMiddleware>();
}

然后就是看下ResponseCachingMiddleware。

public ResponseCachingMiddleware(
	RequestDelegate next,
	IOptions<ResponseCachingOptions> options,
	ILoggerFactory loggerFactory,
	ObjectPoolProvider poolProvider)
	: this(
		next,
		options,
		loggerFactory,
		new ResponseCachingPolicyProvider(),
		new MemoryResponseCache(new MemoryCache(new MemoryCacheOptions
		{
			SizeLimit = options.Value.SizeLimit
		})),
		new ResponseCachingKeyProvider(poolProvider, options))
{ }

可以看到其使用的cache,是MemoryCache。好的就點到為止吧,后續的可能會寫在細節篇中,可能也不會出現在細節篇中,未在計划內。

好吧,然后測試代碼:

public class OrderController : Controller
{
	[ResponseCache(Duration = 6000)]
	public IActionResult Pay()
	{
		return Content("買買買:"+DateTime.Now);
	}
}

看下效果:

第一次請求的時候:

給了這個參數,告訴瀏覽器,在該段時間內就不要來訪問后台了,用緩存就好。

第二次訪問:

黃色部分的意思該請求沒有發出去,用的是緩存。

感覺這樣挺好的,那么這個時候就有坑來了。

[ResponseCache(Duration = 6000)]
public IActionResult Pay(string name)
{
	return Content("買買買:"+DateTime.Now+name);
}

訪問第一次:

訪問第二次:

顯然第二次是有問題的。

因為name 參數變化了,但是結果相同。

這顯然是有問題的,這是客戶端緩存嗎?不是,瀏覽器只要是訪問鏈接發生任何變化的時候就會不使用。

可以看到上面實際上去訪問了我們的后台的。

那么應該這樣寫,表示當name 參數發生變化的時候就不會命中后台的緩存:

public class OrderController : Controller
{
	[ResponseCache(Duration = 6000,VaryByQueryKeys =new String[]{ "name"})]
	public IActionResult Pay(string name)
	{
		return Content("買買買:"+DateTime.Now+name);
	}
}

為什么這么寫呢?這個就要從后台緩存的key開始說起。

看下:ResponseCache 里面的,也就是這個屬性類。

public CacheProfile GetCacheProfile(MvcOptions options)
{
	CacheProfile selectedProfile = null;
	if (CacheProfileName != null)
	{
		options.CacheProfiles.TryGetValue(CacheProfileName, out selectedProfile);
		if (selectedProfile == null)
		{
			throw new InvalidOperationException(Resources.FormatCacheProfileNotFound(CacheProfileName));
		}
	}

	// If the ResponseCacheAttribute parameters are set,
	// then it must override the values from the Cache Profile.
	// The below expression first checks if the duration is set by the attribute's parameter.
	// If absent, it checks the selected cache profile (Note: There can be no cache profile as well)
	// The same is the case for other properties.
	_duration = _duration ?? selectedProfile?.Duration;
	_noStore = _noStore ?? selectedProfile?.NoStore;
	_location = _location ?? selectedProfile?.Location;
	VaryByHeader = VaryByHeader ?? selectedProfile?.VaryByHeader;
	VaryByQueryKeys = VaryByQueryKeys ?? selectedProfile?.VaryByQueryKeys;

	return new CacheProfile
	{
		Duration = _duration,
		Location = _location,
		NoStore = _noStore,
		VaryByHeader = VaryByHeader,
		VaryByQueryKeys = VaryByQueryKeys,
	};
}

/// <inheritdoc />
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
{
	if (serviceProvider == null)
	{
		throw new ArgumentNullException(nameof(serviceProvider));
	}

	var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
	var optionsAccessor = serviceProvider.GetRequiredService<IOptions<MvcOptions>>();
	var cacheProfile = GetCacheProfile(optionsAccessor.Value);

	// ResponseCacheFilter cannot take any null values. Hence, if there are any null values,
	// the properties convert them to their defaults and are passed on.
	return new ResponseCacheFilter(cacheProfile, loggerFactory);
}

可以看到CreateInstance 生成了一個ResponseCacheFilter。

那么來看下這個ResponseCacheFilter:

/// <summary>
/// Creates a new instance of <see cref="ResponseCacheFilter"/>
/// </summary>
/// <param name="cacheProfile">The profile which contains the settings for
/// <see cref="ResponseCacheFilter"/>.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param>
public ResponseCacheFilter(CacheProfile cacheProfile, ILoggerFactory loggerFactory)
{
	_executor = new ResponseCacheFilterExecutor(cacheProfile);
	_logger = loggerFactory.CreateLogger(GetType());
}

/// <inheritdoc />
public void OnActionExecuting(ActionExecutingContext context)
{
	if (context == null)
	{
		throw new ArgumentNullException(nameof(context));
	}

	// If there are more filters which can override the values written by this filter,
	// then skip execution of this filter.
	var effectivePolicy = context.FindEffectivePolicy<IResponseCacheFilter>();
	if (effectivePolicy != null && effectivePolicy != this)
	{
		_logger.NotMostEffectiveFilter(GetType(), effectivePolicy.GetType(), typeof(IResponseCacheFilter));
		return;
	}

	_executor.Execute(context);
}

那么來看一下ResponseCacheFilterExecutor:

internal class ResponseCacheFilterExecutor
{
	private readonly CacheProfile _cacheProfile;
	private int? _cacheDuration;
	private ResponseCacheLocation? _cacheLocation;
	private bool? _cacheNoStore;
	private string _cacheVaryByHeader;
	private string[] _cacheVaryByQueryKeys;

	public ResponseCacheFilterExecutor(CacheProfile cacheProfile)
	{
		_cacheProfile = cacheProfile ?? throw new ArgumentNullException(nameof(cacheProfile));
	}

	public int Duration
	{
		get => _cacheDuration ?? _cacheProfile.Duration ?? 0;
		set => _cacheDuration = value;
	}

	public ResponseCacheLocation Location
	{
		get => _cacheLocation ?? _cacheProfile.Location ?? ResponseCacheLocation.Any;
		set => _cacheLocation = value;
	}

	public bool NoStore
	{
		get => _cacheNoStore ?? _cacheProfile.NoStore ?? false;
		set => _cacheNoStore = value;
	}

	public string VaryByHeader
	{
		get => _cacheVaryByHeader ?? _cacheProfile.VaryByHeader;
		set => _cacheVaryByHeader = value;
	}

	public string[] VaryByQueryKeys
	{
		get => _cacheVaryByQueryKeys ?? _cacheProfile.VaryByQueryKeys;
		set => _cacheVaryByQueryKeys = value;
	}

	public void Execute(FilterContext context)
	{
		if (context == null)
		{
			throw new ArgumentNullException(nameof(context));
		}

		if (!NoStore)
		{
			// Duration MUST be set (either in the cache profile or in this filter) unless NoStore is true.
			if (_cacheProfile.Duration == null && _cacheDuration == null)
			{
				throw new InvalidOperationException(
					Resources.FormatResponseCache_SpecifyDuration(nameof(NoStore), nameof(Duration)));
			}
		}

		var headers = context.HttpContext.Response.Headers;

		// Clear all headers
		headers.Remove(HeaderNames.Vary);
		headers.Remove(HeaderNames.CacheControl);
		headers.Remove(HeaderNames.Pragma);

		if (!string.IsNullOrEmpty(VaryByHeader))
		{
			headers[HeaderNames.Vary] = VaryByHeader;
		}

		if (VaryByQueryKeys != null)
		{
			var responseCachingFeature = context.HttpContext.Features.Get<IResponseCachingFeature>();
			if (responseCachingFeature == null)
			{
				throw new InvalidOperationException(
					Resources.FormatVaryByQueryKeys_Requires_ResponseCachingMiddleware(nameof(VaryByQueryKeys)));
			}
			responseCachingFeature.VaryByQueryKeys = VaryByQueryKeys;
		}

		if (NoStore)
		{
			headers[HeaderNames.CacheControl] = "no-store";

			// Cache-control: no-store, no-cache is valid.
			if (Location == ResponseCacheLocation.None)
			{
				headers.AppendCommaSeparatedValues(HeaderNames.CacheControl, "no-cache");
				headers[HeaderNames.Pragma] = "no-cache";
			}
		}
		else
		{
			string cacheControlValue;
			switch (Location)
			{
				case ResponseCacheLocation.Any:
					cacheControlValue = "public,";
					break;
				case ResponseCacheLocation.Client:
					cacheControlValue = "private,";
					break;
				case ResponseCacheLocation.None:
					cacheControlValue = "no-cache,";
					headers[HeaderNames.Pragma] = "no-cache";
					break;
				default:
					cacheControlValue = null;
					break;
			}

			cacheControlValue = $"{cacheControlValue}max-age={Duration}";
			headers[HeaderNames.CacheControl] = cacheControlValue;
		}
	}

看里面的Execute,這個。

可以看到對於我們的VaryByQueryKeys,其傳遞給了一個叫做IResponseCachingFeature的子類。

那么什么時候用到了呢?

就在我們中間件的ResponseCachingMiddleware的OnFinalizeCacheHeaders方法中。

/// <summary>
/// Finalize cache headers.
/// </summary>
/// <param name="context"></param>
/// <returns><c>true</c> if a vary by entry needs to be stored in the cache; otherwise <c>false</c>.</returns>
private bool OnFinalizeCacheHeaders(ResponseCachingContext context)
{
	if (_policyProvider.IsResponseCacheable(context))
	{
		var storeVaryByEntry = false;
		context.ShouldCacheResponse = true;

		// Create the cache entry now
		var response = context.HttpContext.Response;
		var varyHeaders = new StringValues(response.Headers.GetCommaSeparatedValues(HeaderNames.Vary));
		var varyQueryKeys = new StringValues(context.HttpContext.Features.Get<IResponseCachingFeature>()?.VaryByQueryKeys);
		context.CachedResponseValidFor = context.ResponseSharedMaxAge ??
			context.ResponseMaxAge ??
			(context.ResponseExpires - context.ResponseTime.Value) ??
			DefaultExpirationTimeSpan;

		// Generate a base key if none exist
		if (string.IsNullOrEmpty(context.BaseKey))
		{
			context.BaseKey = _keyProvider.CreateBaseKey(context);
		}

		// Check if any vary rules exist
		if (!StringValues.IsNullOrEmpty(varyHeaders) || !StringValues.IsNullOrEmpty(varyQueryKeys))
		{
			// Normalize order and casing of vary by rules
			var normalizedVaryHeaders = GetOrderCasingNormalizedStringValues(varyHeaders);
			var normalizedVaryQueryKeys = GetOrderCasingNormalizedStringValues(varyQueryKeys);

			// Update vary rules if they are different
			if (context.CachedVaryByRules == null ||
				!StringValues.Equals(context.CachedVaryByRules.QueryKeys, normalizedVaryQueryKeys) ||
				!StringValues.Equals(context.CachedVaryByRules.Headers, normalizedVaryHeaders))
			{
				context.CachedVaryByRules = new CachedVaryByRules
				{
					VaryByKeyPrefix = FastGuid.NewGuid().IdString,
					Headers = normalizedVaryHeaders,
					QueryKeys = normalizedVaryQueryKeys
				};
			}

			// Always overwrite the CachedVaryByRules to update the expiry information
			_logger.VaryByRulesUpdated(normalizedVaryHeaders, normalizedVaryQueryKeys);
			storeVaryByEntry = true;

			context.StorageVaryKey = _keyProvider.CreateStorageVaryByKey(context);
		}

		// Ensure date header is set
		if (!context.ResponseDate.HasValue)
		{
			context.ResponseDate = context.ResponseTime.Value;
			// Setting the date on the raw response headers.
			context.HttpContext.Response.Headers[HeaderNames.Date] = HeaderUtilities.FormatDate(context.ResponseDate.Value);
		}

		// Store the response on the state
		context.CachedResponse = new CachedResponse
		{
			Created = context.ResponseDate.Value,
			StatusCode = context.HttpContext.Response.StatusCode,
			Headers = new HeaderDictionary()
		};

		foreach (var header in context.HttpContext.Response.Headers)
		{
			if (!string.Equals(header.Key, HeaderNames.Age, StringComparison.OrdinalIgnoreCase))
			{
				context.CachedResponse.Headers[header.Key] = header.Value;
			}
		}

		return storeVaryByEntry;
	}

	context.ResponseCachingStream.DisableBuffering();
	return false;
}

重點關注一下context.StorageVaryKey 是如何生成的,StorageVaryKey就是緩存的key。

if (context.CachedVaryByRules == null ||
	!StringValues.Equals(context.CachedVaryByRules.QueryKeys, normalizedVaryQueryKeys) ||
	!StringValues.Equals(context.CachedVaryByRules.Headers, normalizedVaryHeaders))
{
	context.CachedVaryByRules = new CachedVaryByRules
	{
		VaryByKeyPrefix = FastGuid.NewGuid().IdString,
		Headers = normalizedVaryHeaders,
		QueryKeys = normalizedVaryQueryKeys
	};
}

context.StorageVaryKey = _keyProvider.CreateStorageVaryByKey(context);

那么可以看下CreateStorageVaryByKey:

// BaseKey<delimiter>H<delimiter>HeaderName=HeaderValue<delimiter>Q<delimiter>QueryName=QueryValue1<subdelimiter>QueryValue2
public string CreateStorageVaryByKey(ResponseCachingContext context)
{
	if (context == null)
	{
		throw new ArgumentNullException(nameof(context));
	}

	var varyByRules = context.CachedVaryByRules;
	if (varyByRules == null)
	{
		throw new InvalidOperationException($"{nameof(CachedVaryByRules)} must not be null on the {nameof(ResponseCachingContext)}");
	}

	if (StringValues.IsNullOrEmpty(varyByRules.Headers) && StringValues.IsNullOrEmpty(varyByRules.QueryKeys))
	{
		return varyByRules.VaryByKeyPrefix;
	}

	var request = context.HttpContext.Request;
	var builder = _builderPool.Get();

	try
	{
		// Prepend with the Guid of the CachedVaryByRules
		builder.Append(varyByRules.VaryByKeyPrefix);

		// Vary by headers
		var headersCount = varyByRules?.Headers.Count ?? 0;
		if (headersCount > 0)
		{
			// Append a group separator for the header segment of the cache key
			builder.Append(KeyDelimiter)
				.Append('H');

			var requestHeaders = context.HttpContext.Request.Headers;
			for (var i = 0; i < headersCount; i++)
			{
				var header = varyByRules.Headers[i];
				var headerValues = requestHeaders[header];
				builder.Append(KeyDelimiter)
					.Append(header)
					.Append('=');

				var headerValuesArray = headerValues.ToArray();
				Array.Sort(headerValuesArray, StringComparer.Ordinal);

				for (var j = 0; j < headerValuesArray.Length; j++)
				{
					builder.Append(headerValuesArray[j]);
				}
			}
		}

		// Vary by query keys
		if (varyByRules?.QueryKeys.Count > 0)
		{
			// Append a group separator for the query key segment of the cache key
			builder.Append(KeyDelimiter)
				.Append('Q');

			if (varyByRules.QueryKeys.Count == 1 && string.Equals(varyByRules.QueryKeys[0], "*", StringComparison.Ordinal))
			{
				// Vary by all available query keys
				var queryArray = context.HttpContext.Request.Query.ToArray();
				// Query keys are aggregated case-insensitively whereas the query values are compared ordinally.
				Array.Sort(queryArray, QueryKeyComparer.OrdinalIgnoreCase);

				for (var i = 0; i < queryArray.Length; i++)
				{
					builder.Append(KeyDelimiter)
						.AppendUpperInvariant(queryArray[i].Key)
						.Append('=');

					var queryValueArray = queryArray[i].Value.ToArray();
					Array.Sort(queryValueArray, StringComparer.Ordinal);

					for (var j = 0; j < queryValueArray.Length; j++)
					{
						if (j > 0)
						{
							builder.Append(KeySubDelimiter);
						}

						builder.Append(queryValueArray[j]);
					}
				}
			}
			else
			{
				for (var i = 0; i < varyByRules.QueryKeys.Count; i++)
				{
					var queryKey = varyByRules.QueryKeys[i];
					var queryKeyValues = context.HttpContext.Request.Query[queryKey];
					builder.Append(KeyDelimiter)
						.Append(queryKey)
						.Append('=');

					var queryValueArray = queryKeyValues.ToArray();
					Array.Sort(queryValueArray, StringComparer.Ordinal);

					for (var j = 0; j < queryValueArray.Length; j++)
					{
						if (j > 0)
						{
							builder.Append(KeySubDelimiter);
						}

						builder.Append(queryValueArray[j]);
					}
				}
			}
		}

		return builder.ToString();
	}
	finally
	{
		_builderPool.Return(builder);
	}
}

可以看到如果緩存的key值和我們的VaryByQueryKeys的設置息息相關,只要我們的VaryByQueryKeys設置的key的value發生任何變化,也就是我們的參數的值發生變化,那么生成的緩存key絕對不同,那么就不會命中。

下面就簡單介紹一下redis的緩存。

services.AddStackExchangeRedisCache(options =>
{
	Configuration.GetSection("redisCache").Bind(options);
});

這樣就是redis的緩存。

然后第三方就是easycache 就是:

services.AddEasyCaching(options =>
{
	options.UseRedis(Configuration,name:"easycaching");
});

這些都可以直接去看文檔,這里覺得沒什么要整理的。

下一節 apollo 配置中心。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM