C # cache implementation

Implementation of Cache

We are not doing a third-party cache implementation such as Redis, but according to the actual situation, we will save some environment variables based on C# to facilitate the use of the project.

1. System global variables

Many times, when the system starts, it is necessary to save the operating parameters of the system for global use.

The code is as follows:

 public class PFTCacheObject

{
///
/// Dictionary
///

private static Dictionary<string, object> _dataDic = new Dictionary<string, object>();


///
/// Define a static variable to save the instance of the class
///

private static PFTCacheObject _session;

///
/// Define an identifier to ensure thread synchronization
///

private static readonly object _locker = new object();


///
/// Singleton
///

/// The return type is Session
public static PFTCacheObject Instance
{
get
{
if (_session == null)
{
lock (_locker)
{
if (_session == null)// If the instance of the class does not exist, create it, otherwise return directly
{
_session = new PFTCacheObject();
}
}
}
return _session;
}
}

#region Remove Remove

///
/// Delete members
///

///
public void Remove(string name)
{
_dataDic.Remove(name);
}

///
/// Delete all members
///

public void RemoveAll()
{
_dataDic.Clear();
}
#endregion

#region Indexer of this category

///
/// Indexer of this category
///

/// Return to Object members
public Object this[string index]
{
get
{
if (_dataDic.ContainsKey(index))
{
Object obj = (Object)_dataDic[index];
return obj;
}
return null;
}
set
{
if (_dataDic.ContainsKey(index))
{
_dataDic.Remove(index);
}
_dataDic.Add(index, value);
}
}
#endregion


}

Here, a Dictionary of static variables is used to save, and all items can be obtained directly.

2, asynchronous data caching

On the web, HttpContext.Current.Items is often used for data caching, and CallContext.LogicalSetData is used on the .Net Framework framework. CallContext.LogicalSetData can no longer be used in .Net Standard. The method to replace it is AsyncLocal. Because we are now using .Net Standard, and our project is not just the web, so here we only use AsyncLocal to achieve.

The code is as follows

public class PFTCallContext

{

#region Shared database connection

private static AsyncLocal<object> _asyncLocalConnectionOject = new AsyncLocal<object>();

///
/// Set up shared database connection
///

///
public static void SetConnectionOject(object obj)
{
_asyncLocalConnectionOject.Value = obj;
}

///
/// Get shared database connection
///

///
public static object GetConnectionOject()
{
return _asyncLocalConnectionOject.Value;
}

///
/// Clear shared database connection
///

public static void ClearConnectionOject()
{
_asyncLocalConnectionOject.Value = null;
}

#endregion



}

Here we first define a cache of the current database connection object. If you need other definitions, you can implement them directly.

3. MemoryCache of .Net Core

I originally wanted to use the cache in the .Net Framework framework, but .Net Core is the future trend, and the .Net Framework’s There are already many ways to implement the cache, so here I will directly use the MemoryCache of .Net Core. The .Net Core snail is also learning, and related APIs are constantly being studied. If there is a problem, please help me to correct it.

public static < span style="color: #0000ff;">class PFTCache

{
public readonly static IMemoryCache _memoryCache;

static PFTCache()
{
_memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions()) );
}

#region Regular cache
///
/// Get the cached value
///

///
///
public static Object GetCache(string key)
{
return _memoryCache.Get(key);
}
///
/// Remove cache
///

///
public static void Remove(string key)
{
_memoryCache.Remove(key);
}
///
/// Set cache
///

///
///
public static void SetCache(string key, Object value)
{
_memoryCache.GetOrCreate(key, entry =>
{
return value;
});
}
///
/// Set cache (fixed time expires)
///

///
///
///
public static void SetCacheAbsolute(string key, Object value, int absoluteExpiration)
{
_memoryCache.GetOrCreate(key, entry =>
{

entry.SetAbsoluteExpiration(TimeSpan.FromSeconds(absoluteExpiration));
return value;
});
}
///
/// Set cache (rolling time expires)
///

///
///
///
public static void SetCacheSliding(string key, Object value, int slidingExpiration)
{
_memoryCache.GetOrCreate(key, entry =>
{

entry.SetSlidingExpiration(TimeSpan.FromSeconds(slidingExpiration));
return value;
});
}

#endregion

#region file dependent cache
///
/// File dependent cache
///

///
///
///
public static string DependentCacheFile(string key, string fullName)
{
var basePath = PFTFile.GetDirectoryName(fullName);
var fileName = PFTFile.GetFileName(fullName);
var fileProvider = new PhysicalFileProvider(basePath);
return _memoryCache.GetOrCreate(key, entry =>
{
entry.AddExpirationToken(fileProvider.Watch(fileName));
return PFTFile.IsExistFile(fullName)? PFTFile.ReadFile(fullName): string span>.Empty;
});
}
#endregion

}

Okay, let’s stop here for the snail of caching.

 public class PFTCacheObject

{
///
/// Dictionary
///

private static Dictionary<string, object> _dataDic = new Dictionary<string, object>();


///
/// Define a static variable to save the instance of the class
///

private static PFTCacheObject _session;

///
/// Define an identifier to ensure thread synchronization
///

private static readonly object _locker = new object();


///
/// Singleton
///

/// The return type is Session
public static PFTCacheObject Instance
{
get
{
if (_session == null)
{
lock (_locker)
{
if (_session == null)// If the instance of the class does not exist, create it, otherwise return directly
{
_session = new PFTCacheObject();
}
}
}
return _session;
}
}

#region Remove Remove

///
/// Delete members
///

///
public void Remove(string name)
{
_dataDic.Remove(name);
}

///
/// Delete all members
///

public void RemoveAll()
{
_dataDic.Clear();
}
#endregion

#region Indexer of this category

///
/// Indexer of this category
///

/// Return to Object members
public Object this[string index]
{
get
{
if (_dataDic.ContainsKey(index))
{
Object obj = (Object)_dataDic[index];
return obj;
}
return null;
}
set
{
if (_dataDic.ContainsKey(index))
{
_dataDic.Remove(index);
}
_dataDic.Add(index, value);
}
}
#endregion


}

public class< /span> PFTCallContext

{

#region Shared database connection

private static AsyncLocal<object> _asyncLocalConnectionOject = new AsyncLocal<object>();

///
/// Set up shared database connection
///

///
public static void SetConnectionOject(object obj)
{
_asyncLocalConnectionOject.Value = obj;
}

///
/// Get shared database connection
///

///
public static object GetConnectionOject()
{
return _asyncLocalConnectionOject.Value;
}

///
/// Clear shared database connection
///

public static void ClearConnectionOject()
{
_asyncLocalConnectionOject.Value = null;
}

#endregion



}

public static< /span> class PFTCache

{
public readonly static IMemoryCache _memoryCache;

static PFTCache()
{
_memoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions()) );
}

#region Regular cache
///
/// Get the cached value
///

///
///
public static Object GetCache(string key)
{
return _memoryCache.Get(key);
}
///
/// Remove cache
///

///
public static void Remove(string key)
{
_memoryCache.Remove(key);
}
///
/// Set cache
///

///
///
public static void SetCache(string key, Object value)
{
_memoryCache.GetOrCreate(key, entry =>
{
return value;
});
}
///
/// Set cache (fixed time expires)
///

///
///
///
public static void SetCacheAbsolute(string key, Object value, int absoluteExpiration)
{
_memoryCache.GetOrCreate(key, entry =>
{

entry.SetAbsoluteExpiration(TimeSpan.FromSeconds(absoluteExpiration));
return value;
});
}
///
/// Set cache (rolling time expires)
///

///
///
///
public static void SetCacheSliding(string key, Object value, int slidingExpiration)
{
_memoryCache.GetOrCreate(key, entry =>
{

entry.SetSlidingExpiration(TimeSpan.FromSeconds(slidingExpiration));
return value;
});
}

#endregion

#region file dependent cache
///
/// File dependent cache
///

///
///
///
public static string DependentCacheFile(string key, string fullName)
{
var basePath = PFTFile.GetDirectoryName(fullName);
var fileName = PFTFile.GetFileName(fullName);
var fileProvider = new PhysicalFileProvider(basePath);
return _memoryCache.GetOrCreate(key, entry =>
{
entry.AddExpirationToken(fileProvider.Watch(fileName));
return PFTFile.IsExistFile(fullName)? PFTFile.ReadFile(fullName): string span>.Empty;
});
}
#endregion

}

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3057 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.