当前位置: 首页>后端>正文

Util应用框架基础(七)- API

API

Util应用框架缓存操作API

ICache

概述

Util.Caching.ICache 是缓存操作的主要接口.

根据缓存配置,ICache可以在本地缓存,Redis缓存,2级缓存切换.

  • 如果仅配置本地缓存, ICache实例为本地缓存操作.

  • 如果仅配置 Redis 缓存,ICache实例为Redis缓存操作.

  • 如果同时配置本地缓存和 Redis 缓存,ICache 实例为后配置的缓存操作.

  • 如果配置了2级缓存,ICache 实例为2级缓存操作.

注意事项

如果使用2级缓存,有些操作不可用,调用会抛出异常.

示例上下文

  • 通过依赖注入获取 ICache 实例.

    public class Service : IService {
      private ICache _cache;
      private IUserResourceRepository _repository;
    
      public Service( ICache cache,IUserResourceRepository repository ) {
          _cache = cache;
          _repository = repository;
      }
    }
    
  • 用户资源示例

    public class UserResource {
        public string UserId { get; set; }
        public string UserName { get; set; }
        public string ResourceId { get; set; }
        public string ResourceName { get; set; }
    }
    
  • 用户资源缓存键示例

    public class UserResourceCacheKey : CacheKey {
        public UserResourceCacheKey( string userId,string resourceId ) {
            Prefix = $"User-{userId}:";
            Key = $"Resource-{resourceId}";
        }
    }
    
  • 用户资源仓储示例

    public interface IUserResourceRepository {
      UserResource GetUserResource( string userId, string resourceId );
      Task<UserResource> GetUserResourceAsync( string userId, string resourceId );
    }
    

API

  • Exists

    功能: 判断缓存是否存在

    • bool Exists( CacheKey key )

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      bool exists = _cache.Exists( cacheKey );
      
    • bool Exists( string key )

      范例:

      bool exists = _cache.Exists( "User-1:Resource-2" );
      
  • ExistsAsync

    功能: 判断缓存是否存在

    • Task<bool> ExistsAsync( CacheKey key, CancellationToken cancellationToken = default )

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      bool exists = await _cache.ExistsAsync( cacheKey );
      
    • Task<bool> ExistsAsync( string key, CancellationToken cancellationToken = default )

      范例:

      bool exists = await _cache.ExistsAsync( "User-1:Resource-2" );
      
  • Get

    功能: 从缓存中获取数据

    • T Get<T>( CacheKey key )

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var result = _cache.Get<UserResource>( cacheKey );
      
    • T Get<T>( string key )

      范例:

      var result = _cache.Get<UserResource>( "User-1:Resource-2" );
      
    • List<T> Get<T>( IEnumerable<CacheKey> keys )

      通过缓存键集合获取结果集合.

      范例:

      var keys = new List<UserResourceCacheKey> { new ( "1", "2" ), new( "3", "4" ) };
      var result = _cache.Get<UserResource>( keys );
      
    • List<T> Get<T>( IEnumerable<string> keys )

      通过缓存键集合获取结果集合.

      范例:

      var keys = new List<string> { "User-1:Resource-2", "User-3:Resource-4" };
      var result = _cache.Get<UserResource>( keys );
      
    • T Get<T>( CacheKey key, Func<T> action, CacheOptions options = null )

      从缓存中获取数据,如果数据不存在,则执行获取数据操作并添加到缓存中.

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var result = _cache.Get( cacheKey,()=> _repository.GetUserResource( "1", "2" ) );
      

      CacheOptions 配置包含 Expiration 属性,用于设置缓存过期时间间隔,默认值: 8小时.

      设置1小时过期,如下所示.

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var result = _cache.Get( cacheKey, () => _repository.GetUserResource( "1", "2" ), new CacheOptions { Expiration = TimeSpan.FromHours( 1 ) } );
      
    • T Get<T>( string key, Func<T> action, CacheOptions options = null )

      从缓存中获取数据,如果数据不存在,则执行获取数据操作并添加到缓存中.

      范例:

      var result = _cache.Get( "User-1:Resource-2",()=> _repository.GetUserResource( "1", "2" ) );
      
  • GetAsync

    功能: 从缓存中获取数据

    • Task<object> GetAsync( string key, Type type, CancellationToken cancellationToken = default )

      无法传入泛型返回类型参数可使用该重载方法.

      范例:

      object result = await _cache.GetAsync( "User-1:Resource-2", typeof( UserResource ) );
      
    • Task<T> GetAsync<T>( CacheKey key, CancellationToken cancellationToken = default )

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var result = await _cache.GetAsync<UserResource>( cacheKey );
      
    • Task<T> GetAsync<T>( string key, CancellationToken cancellationToken = default )

      范例:

      var result = await _cache.GetAsync<UserResource>( "User-1:Resource-2" );
      
    • Task<List<T>> GetAsync<T>( IEnumerable<CacheKey> keys, CancellationToken cancellationToken = default )

      通过缓存键集合获取结果集合.

      范例:

      var keys = new List<UserResourceCacheKey> { new ( "1", "2" ), new( "3", "4" ) };
      var result = await _cache.GetAsync<UserResource>( keys );
      
    • Task<List<T>> GetAsync<T>( IEnumerable<string> keys, CancellationToken cancellationToken = default )

      通过缓存键集合获取结果集合.

      范例:

      var keys = new List<string> { "User-1:Resource-2", "User-3:Resource-4" };
      var result = await _cache.GetAsync<UserResource>( keys );
      
    • Task<T> GetAsync<T>( CacheKey key, Func<Task<T>> action, CacheOptions options = null, CancellationToken cancellationToken = default )

      从缓存中获取数据,如果数据不存在,则执行获取数据操作并添加到缓存中.

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var result = await _cache.GetAsync( cacheKey,async ()=> await _repository.GetUserResourceAsync( "1", "2" ) );
      

      CacheOptions 配置包含 Expiration 属性,用于设置缓存过期时间间隔,默认值: 8小时.

      设置1小时过期,如下所示.

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var result = await _cache.GetAsync( cacheKey,async ()=> await _repository.GetUserResourceAsync( "1", "2" ), new CacheOptions { Expiration = TimeSpan.FromHours( 1 ) } );
      
    • Task<T> GetAsync<T>( string key, Func<Task<T>> action, CacheOptions options = null, CancellationToken cancellationToken = default )

      从缓存中获取数据,如果数据不存在,则执行获取数据操作并添加到缓存中.

      范例:

      var result = await _cache.GetAsync( "User-1:Resource-2",async ()=> await _repository.GetUserResourceAsync( "1", "2" ) );
      
  • GetByPrefix

    功能: 通过缓存键前缀获取数据

    • List<T> GetByPrefix<T>( string prefix )

      范例:

      var result = _cache.GetByPrefix<UserResource>( "User-1" );
      
  • GetByPrefixAsync

    功能: 通过缓存键前缀获取数据

    • Task<List<T>> GetByPrefixAsync<T>( string prefix, CancellationToken cancellationToken = default )

      范例:

      var result = await _cache.GetByPrefixAsync<UserResource>( "User-1" );
      
  • TrySet

    功能: 设置缓存,当缓存已存在则忽略,设置成功返回true

    • bool TrySet<T>( CacheKey key, T value, CacheOptions options = null )

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var value = _repository.GetUserResource( "1", "2" );
      var result = _cache.TrySet( cacheKey, value );
      

      CacheOptions 配置包含 Expiration 属性,用于设置缓存过期时间间隔,默认值: 8小时.

      设置1小时过期,如下所示.

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var value = _repository.GetUserResource( "1", "2" );
      var result = _cache.TrySet( cacheKey, value, new CacheOptions { Expiration = TimeSpan.FromHours( 1 ) } );
      
    • bool TrySet<T>( string key, T value, CacheOptions options = null )

      范例:

      var value = _repository.GetUserResource( "1", "2" );
      var result = _cache.TrySet( "User-1:Resource-2", value );
      
  • TrySetAsync

    功能: 设置缓存,当缓存已存在则忽略,设置成功返回true

    • Task<bool> TrySetAsync<T>( CacheKey key, T value, CacheOptions options = null, CancellationToken cancellationToken = default )

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var value = await _repository.GetUserResourceAsync( "1", "2" );
      var result = await _cache.TrySetAsync( cacheKey, value );
      

      CacheOptions 配置包含 Expiration 属性,用于设置缓存过期时间间隔,默认值: 8小时.

      设置1小时过期,如下所示.

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var value = await _repository.GetUserResourceAsync( "1", "2" );
      var result = await _cache.TrySetAsync( cacheKey, value, new CacheOptions { Expiration = TimeSpan.FromHours( 1 ) } );
      
    • Task<bool> TrySetAsync<T>( string key, T value, CacheOptions options = null, CancellationToken cancellationToken = default )

      范例:

      var value = await _repository.GetUserResourceAsync( "1", "2" );
      var result = await _cache.TrySetAsync( "User-1:Resource-2", value );
      
  • Set

    功能: 设置缓存,当缓存已存在则覆盖

    • void Set<T>( CacheKey key, T value, CacheOptions options = null )

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var value = _repository.GetUserResource( "1", "2" );
      _cache.Set( cacheKey, value );
      

      CacheOptions 配置包含 Expiration 属性,用于设置缓存过期时间间隔,默认值: 8小时.

      设置1小时过期,如下所示.

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var value = _repository.GetUserResource( "1", "2" );
      _cache.Set( cacheKey, value, new CacheOptions { Expiration = TimeSpan.FromHours( 1 ) } );
      
    • void Set<T>( string key, T value, CacheOptions options = null )

      范例:

      var value = _repository.GetUserResource( "1", "2" );
      _cache.Set( "User-1:Resource-2", value );
      
    • void Set<T>( IDictionary<CacheKey,T> items, CacheOptions options = null )

      范例:

      var items = new Dictionary<CacheKey, UserResource> {
          { new UserResourceCacheKey( "1", "2" ), _repository.GetUserResource( "1", "2" ) },
          { new UserResourceCacheKey( "3", "4" ), _repository.GetUserResource( "3", "4" ) }
      };
      _cache.Set( items );
      
    • void Set<T>( IDictionary<string,T> items, CacheOptions options = null )

      范例:

      var items = new Dictionary<string, UserResource> {
          { "User-1:Resource-2", _repository.GetUserResource( "1", "2" ) },
          { "User-3:Resource-4", _repository.GetUserResource( "3", "4" ) }
      };
      _cache.Set( items );
      
  • SetAsync

    功能: 设置缓存,当缓存已存在则覆盖

    • Task SetAsync<T>( CacheKey key, T value, CacheOptions options = null, CancellationToken cancellationToken = default )

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var value = await _repository.GetUserResourceAsync( "1", "2" );
      await _cache.SetAsync( cacheKey, value );
      

      CacheOptions 配置包含 Expiration 属性,用于设置缓存过期时间间隔,默认值: 8小时.

      设置1小时过期,如下所示.

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      var value = await _repository.GetUserResourceAsync( "1", "2" );
      await _cache.SetAsync( cacheKey, value, new CacheOptions { Expiration = TimeSpan.FromHours( 1 ) } );
      
    • Task SetAsync<T>( string key, T value, CacheOptions options = null, CancellationToken cancellationToken = default )

      范例:

      var value = await _repository.GetUserResourceAsync( "1", "2" );
      await _cache.SetAsync( "User-1:Resource-2", value );
      
    • Task SetAsync<T>( IDictionary<CacheKey, T> items, CacheOptions options = null, CancellationToken cancellationToken = default )

      范例:

      var items = new Dictionary<CacheKey, UserResource> {
          { new UserResourceCacheKey( "1", "2" ), await _repository.GetUserResourceAsync( "1", "2" ) },
          { new UserResourceCacheKey( "3", "4" ), await _repository.GetUserResourceAsync( "3", "4" ) }
      };
      await _cache.SetAsync( items );
      
    • Task SetAsync<T>( IDictionary<string, T> items, CacheOptions options = null, CancellationToken cancellationToken = default )

      范例:

      var items = new Dictionary<string, UserResource> {
          { "User-1:Resource-2", await _repository.GetUserResourceAsync( "1", "2" ) },
          { "User-3:Resource-4", await _repository.GetUserResourceAsync( "3", "4" ) }
      };
      await _cache.SetAsync( items );
      
  • Remove

    功能: 移除缓存

    • void Remove( CacheKey key )

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      _cache.Remove( cacheKey );
      
    • void Remove( string key )

      范例:

      _cache.Remove( "User-1:Resource-2" );
      
    • void Remove( IEnumerable<CacheKey> keys )

      范例:

      var keys = new List<UserResourceCacheKey> { new ( "1", "2" ), new( "3", "4" ) };
      _cache.Remove( keys );
      
    • void Remove( IEnumerable<string> keys )

      范例:

      var keys = new List<string> { "User-1:Resource-2", "User-3:Resource-4" };
      _cache.Remove( keys );
      
  • RemoveAsync

    功能: 移除缓存

    • Task RemoveAsync( CacheKey key, CancellationToken cancellationToken = default )

      范例:

      var cacheKey = new UserResourceCacheKey( "1", "2" );
      await _cache.RemoveAsync( cacheKey );
      
    • Task RemoveAsync( string key, CancellationToken cancellationToken = default )

      范例:

      await _cache.RemoveAsync( "User-1:Resource-2" );
      
    • Task RemoveAsync( IEnumerable<CacheKey> keys, CancellationToken cancellationToken = default )

      范例:

      var keys = new List<UserResourceCacheKey> { new( "1", "2" ), new( "3", "4" ) };
      await _cache.RemoveAsync( keys );
      
    • Task RemoveAsync( IEnumerable<string> keys, CancellationToken cancellationToken = default )

      范例:

      var keys = new List<string> { "User-1:Resource-2", "User-3:Resource-4" };
      await _cache.RemoveAsync( keys );
      
  • RemoveByPrefix

    功能: 通过缓存键前缀移除缓存

    • void RemoveByPrefix( string prefix )

      范例:

      _cache.RemoveByPrefix( "User-1" );
      
    • Task RemoveByPrefixAsync( string prefix, CancellationToken cancellationToken = default )

      范例:

      await _cache.RemoveByPrefixAsync( "User-1" );
      
  • RemoveByPattern

    功能: 通过模式移除缓存

    • void RemoveByPattern( string pattern )

      范例:

      移除 User 开头的缓存.

      _cache.RemoveByPattern( "User*" );
      
  • RemoveByPatternAsync

    功能: 通过模式移除缓存

    • Task RemoveByPatternAsync( string pattern, CancellationToken cancellationToken = default )

      范例:

      移除 User 开头的缓存.

      await _cache.RemoveByPatternAsync( "User*" );
      
  • Clear

    功能: 清空缓存

    • void Clear()

      范例:

      _cache.Clear();
      
  • ClearAsync

    功能: 清空缓存

    • Task ClearAsync( CancellationToken cancellationToken = default )

      范例:

      await _cache.ClearAsync();
      

ILocalCache

Util.Caching.ILocalCache 从 ICache 派生,表示本地缓存.

当同时配置本地缓存和Redis缓存, 如果你想明确使用本地缓存, 请使用 ILocalCache.

Api 参考 ICache.

IRedisCache

Util.Caching.IRedisCache 从 ICache 派生,表示 Redis 分布式缓存.

当同时配置本地缓存和Redis缓存, 如果你想明确使用 Redis 缓存, 请使用 IRedisCache.

IRedisCache 除了继承基础缓存操作外,还将添加 Redis 专用缓存操作.

目前 IRedisCache 尚未添加 Redis 专用操作,后续根据需要进行添加.

Api 参考 ICache.

CacheAttribute

[Cache] 是一个缓存拦截器,使用 ICache 接口操作缓存.

  • API

    • Prefix

      功能: 设置缓存键前缀.

      缓存键前缀支持占位符, {0} 代表第一个参数.

      范例:

      public interface ITestService {
          [Cache( Prefix = "User-{0}" )]
          UserResource Get( string userId, string resourceId );
      }
      

      下面的示例调用 ITestService 的 Get 方法,传入参数 userId = "1" , resourceId = "2" .

      创建的缓存键为: "User-1:1:2".

      缓存键前缀 User-{0} 中的 {0} 替换为第一个参数 userId ,即 User-1.

      使用 : 按顺序连接所有参数值.

      var result = _service.Get( "1", "2" );
      
    • Expiration

      功能: 设置缓存过期间隔,单位: 秒,默认值: 36000

      范例:

      设置 120 秒过期.

      public interface ITestService {
          [Cache( Expiration = 120 )]
          UserResource Get( string userId, string resourceId );
      }
      

LocalCacheAttribute

[LocalCache] 与 [Cache] 类似,但它使用 ILocalCache 接口操作缓存.

如果你的某个操作需要使用本地缓存,可以用 [LocalCache].

API 请参考 [Cache].

RedisCacheAttribute

[RedisCache] 与 [Cache] 类似,但它使用 IRedisCache 接口操作缓存.

如果你的某个操作需要使用Redis缓存,可以用 [RedisCache].

API 请参考 [Cache].


https://www.xamrdz.com/backend/3rj1997539.html

相关文章: