我有一个名为xxxxxx.Bussiness
的类,它不是继承ServiceStack.ServiceInterface
。
但我想使用缓存,怎么做?
答案 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
解析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
定义了这些方法(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)
你必须:
在AppHost中注册CacheClient
public override void Configure(Funq.Container container)
{
//...
container.Register<ICacheClient>(new MemoryCacheClient());
//...
}
在您的服务方法中使用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()
});
}
有一个article on ServiceStack可以更详细地解释缓存使用情况。
注意:以上片段假设使用SS v4.0