如何在servicestack中使用类库注入CacheClient

时间:2014-04-22 03:34:10

标签: servicestack

我有一个名为xxxxxx.Bussiness的类,它不是继承ServiceStack.ServiceInterface

但我想使用缓存,怎么做?

2 个答案:

答案 0 :(得分:1)

如果要访问服务外部的缓存(即继承自ServiceStack.ServiceInterface的类),则可以使用IoC解析方法获取缓存实例。

配置缓存提供程序:

首先,您需要使用Configure AppHost方法在IoC中注册缓存提供程序。 ServiceStack支持许多提供程序。 (内存中,Redis,OrmLite,Memcached,Azure)。有关如何配置所需提供程序的详细信息,请See here以下示例使用内存缓存。

public override void Configure(Funq.Container container)
{
    // Choose the Cache Provider you want to use

    // i.e. Register in Memory Cache Client
    container.Register<ICacheClient>(new MemoryCacheClient());
}

解析ICacheClient:

然后,当您想在服务之外使用缓存时,应尝试使用ICacheClient解析HostContext

var cache = HostContext.TryResolve<ICacheClient>();
if(cache != null)
{
    // Use the cache object
    cache.Add<string>("Key","Value");
    var value = cache.Get<string>("Key");
}

ICacheClient提供了方法:

这将为您提供对缓存的访问权限。 ICacheClient定义了这些方法(Original commented interface definition here):

public interface ICacheClient : IDisposable
{
    bool Remove(string key);
    void RemoveAll(IEnumerable<string> keys);
    T Get<T>(string key);
    long Increment(string key, uint amount);
    long Decrement(string key, uint amount);
    bool Add<T>(string key, T value);
    bool Set<T>(string key, T value);
    bool Replace<T>(string key, T value);
    bool Add<T>(string key, T value, DateTime expiresAt);
    bool Set<T>(string key, T value, DateTime expiresAt);
    bool Replace<T>(string key, T value, DateTime expiresAt);
    bool Add<T>(string key, T value, TimeSpan expiresIn);
    bool Set<T>(string key, T value, TimeSpan expiresIn);
    bool Replace<T>(string key, T value, TimeSpan expiresIn);
    void FlushAll();
    IDictionary<string, T> GetAll<T>(IEnumerable<string> keys);
    void SetAll<T>(IDictionary<string, T> values);
}

转换为缓存提供程序客户端:

您还可以将客户端转换为提供商的特定类型,因为它具有完整功能。例如,如果我们使用Redis缓存:

var cache = HostContext.TryResolve<ICacheClient>() as RedisClient; // Typed
if(cache != null)
{
    var mySet = cache.GetAllItemsFromSet("MySetKey"); // Redis specific cache method
}

我希望这会有所帮助。

答案 1 :(得分:0)

你必须:

  1. 在AppHost中注册CacheClient

    public override void Configure(Funq.Container container)
    {
        //...
    
        container.Register<ICacheClient>(new MemoryCacheClient());
    
        //...
    }          
    
  2. 在您的服务方法中使用Request.ToOptimizedResultUsingCache

    public object Get(Task request)
    {
        return Request.ToOptimizedResultUsingCache(Cache,
            UrnId.Create<Task>("Id", request.Id),
            () => new TaskResponse
            {
                Task = TaskLogicService.GetTask(request.Id),
                ResponseStatus = new ResponseStatus()
            });
    } 
    
  3. 有一个article on ServiceStack可以更详细地解释缓存使用情况。

    注意:以上片段假设使用SS v4.0