Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use caching and configuration in the. Net Core

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to use caching and configuration in. Net Core, the content is concise and easy to understand, and can definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Preface

     caching is an eternal topic in almost all applications. Proper use of caching can effectively improve the performance of applications. In some business scenarios, using cache dependency will have a good experience. In Asp.Net Core, a variety of caching components are supported, of which the most basic and easy to use is IMemoryCache, which indicates that its storage depends on the memory of the managed program server. The following is the IMemoryCache-based cache dependency.

1. Implementation of IMemoryCache

Asp.Net Core internally implements a class MemoryCache that inherits from the IMemoryCache interface

This is almost customary, and once an interface is included in the SDK, it must contain a default implementation

1.1 using IMemoryCache

To use IMemoryCache in Asp.Net Core is very simple, you only need to add a line of code services.AddMemoryCache () to the ConfigureServices method of Startup

1.2 use IMemoryCache in the controller

The above code indicates that an IMemoryCache object is obtained by injection in the constructor of the HomeController controller, a cache record "userId=0001" is added to the Get () method, and then the cache record is extracted in the Get (int id) interface

Run the program and call the Get () and Get (int id) interfaces respectively to get the following output

Call the Get () interface

Call Get (int id) API

This looks very easy, with little thinking, you learn to use caching in Asp.Net Core, easy to use, which is very important, and this is the fundamental attitude that a language is widely promoted.

two。 Apply caching strategy

IMemoryCache also includes a constructor with parameters, which allows us to configure the cache flexibly, which is determined by the class MemoryCacheOptions

2.1 MemoryCacheOptions configuration. There are not many configuration items for MemoryCacheOptions. See the following code.

ISystemClock: system clock. The default value is null. The official document does not specify this property. I do not know what it is for. Which god asks for information about its function and principle?

ExpirationScanFrequency: the interval between scans for expired caches

SizeLimit: the cache can store the number of record entries

CompactionPercentage: percentage of cache compression when cache expiration policy takes effect

The above configuration is very simple, applying code similar to the following in the system

The cache policy above is set to a cache compression ratio of 2%. The expired cache is scanned every 5 minutes, and the maximum cache space is limited to 1024.

The method of use remains unchanged.

2.1 single key caching policy

Since the cache expiration priority of all keys in the cache is the default Normal, we may need to set some cache values to a higher priority in some business scenarios, such as setting never to expire, so that even if the cache reaches the maximum limit, it will not be cleaned up.

Cache priority, which is an enumerated type, which is low, normal, high and never removed. Developers can flexibly set it according to different business scenarios.

To set the policy, use MemoryCacheEntryOptions to apply the policy to a single key

The above code indicates that we have applied a "never remove" strategy to the cache key "userId". Of course, we can also do a lot of strategies for a single value, such as the size of the current value of "userId". Interested students can learn more about the MemoryCacheEntryOptions class.

3. Use cache dependency strategy

Cache dependency means that one or more caches depend on a cache, and when a cache expires, other caches that depend on it also expire. In some application scenarios, cache dependency is very useful.

3.1 register dependency, acquire cache, and remove cache interface after creating TokenController and logging in

The following example uses a business scenario that simulates user login / logout

The above code uses CancellationTokenSource as the event notification source. When the CacheKeys.DependentCTS is removed and the CancellationTokenSource.Cancel () method is triggered, the DependentEvictionCallback (object key, object value, EvictionReason reason, object state) delegate is triggered asynchronously. At this point, the managed program receives a notification that the user has logged out and the user-related cache has been removed. Any removal interface attempts to read the CacheKeys entry again, and the return value is empty.

3.2 run the program, call the login/getkeys/logout interface respectively, and get the following output results

Registration dependency after login login

Getkeys get cache

Logout removes the cache and attempts to read the CacheKeys entry again. At this point, the return value is empty.

Console output removal notification (yellow font section information)

As you can see, in the business scenario of user login and logout, it is very convenient to use cache dependencies to manage their related caches. When users log out, they empty all their related caches.

This paper introduces the simple use of IMemoryCache through an example.

Policies can also be applied to a single cache key

By using the cache dependency strategy, you can have a very good application experience in some business scenarios

Note: when using the global cache policy SizeLimit, each key needs to be set to a size

IMemoryCache relies on memory such as managed servers. Once restarted, cached data will be released immediately.

The above is how to use caching and configuration in .Net Core. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report