[英]General strategy for caching “random” data
I have a website that needs to display a "random" selection of items on its homepage. 我有一个网站,需要在其首页上显示“随机”的项目选择。 This list is somewhat expensive to generate, so I would like to look into performing some caching that still allows the listing to still appear somewhat random to the untrained eye.
此列表的生成有些昂贵,因此我想研究一下执行一些缓存,该缓存仍然允许该列表对于未经训练的人来说仍然显得有些随机。
My idea was to use a randomly-chosen number within a given range (let's say 10, for argument's sake) as part of the cache key. 我的想法是在给定范围内(随机变量,假设为10)使用随机选择的数字作为缓存键的一部分。 Psuedo code would look something like this:
伪代码看起来像这样:
randomCacheVariation = (random number between 1 and 10)
cacheKey = "myRandomList_" + randomCacheVariation
If cache.contains(cacheKey) Then
return existing random list
Else
generate new radom list
add to cache
return list
End If
Does anyone have a better suggestion for how something like this should be implemented? 有谁对应该如何实施这样的建议有更好的建议?
Update: 更新:
Just to be clear, I'm not looking for implementations of caching services, but a strategy of how to cache pseudo-random data by storing some finite number of variations of my list in the cache. 只是要清楚一点,我不是在寻找缓存服务的实现,而是一种通过在缓存中存储我的列表的有限数量的变体来缓存伪随机数据的策略。
Can you generate a "random" list on app startup with maybe 100 items? 您可以在应用启动时生成可能包含100个项目的“随机”列表吗? Then if you need to display 10 "random" items, randomly select from the 100.
然后,如果您需要显示10个“随机”项,请从100个中随机选择。
Supporting documentation: https://stackoverflow.com/questions/462219/xkcd-random-number 支持文档: https : //stackoverflow.com/questions/462219/xkcd-random-number
This is in C# but... 这是在C#中,但是...
public static class Cache
{
public void Add<T>(string key, T item)
{
HttpRuntime.Cache[key] = item;
}
public T Get<T>(string key, Func<T> valueFactory)
{
var obj = HttpRuntime.Cache[key];
if (obj == null)
{
if (valueFactory != null)
{
T tObj = valueFactory();
Add(key, tObj);
return tObj;
}
return default(T);
}
return (T)obj;
}
}
And then you can use it like this... 然后您可以像这样使用它...
var randomSet = Cache.Get<string>("RandomResultSet", () => {
// pull down large random result-set
var randomSet = do stuff;
return randomSet;
});
// Now that we have a large result set cached, let's select a smaller one
var randomStuff = randomSet.GetSmallerRandomSet();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.