jjzjj

c# - ServiceStack.Redis 存储对象超时,key 检索

coder 2023-07-19 原文

我正在尝试使用 ServiceStack.Redis 客户端从 memcached 迁移到 redis。我希望能够简单地检查 Redis 缓存是否有按键项,如果没有则添加它们并设置过期超时。然后稍后检索它们(如果它们存在)。

为了对此进行测试,我创建了一个简单的 ASP.NET WebApi 项目并使用这两种方法修改了 ValuesController。

public class ValuesController : ApiController
{
    public IEnumerable<string> Get()
    {
        using (var redisClient = new RedisClient("localhost"))
        {
            IRedisTypedClient<IEnumerable<SampleEvent>> redis = redisClient.As<IEnumerable<SampleEvent>>();

            if (!redis.ContainsKey("urn:medications:25"))
            {
                var medsWithID25 = new List<SampleEvent>();
                medsWithID25.Add(new SampleEvent() { ID = 1, EntityID = "25", Name = "Digoxin" });
                medsWithID25.Add(new SampleEvent() { ID = 2, EntityID = "25", Name = "Aspirin" });

                redis.SetEntry("urn:medications:25", medsWithID25);
                redis.ExpireIn("urn:medications:25", TimeSpan.FromSeconds(30));
            }

        }

        return new string[] { "1", "2" };
    }

    public SampleEvent Get(int id)
    {
        using (var redisClient = new RedisClient("localhost"))
        {
            IRedisTypedClient<IEnumerable<SampleEvent>> redis = redisClient.As<IEnumerable<SampleEvent>>();
            IEnumerable<SampleEvent> events = redis.GetById("urn:medications:25");

            if (events != null)
            {
                return events.Where(m => m.ID == id).SingleOrDefault();
            }
            else
                return null;
        }
    }
}

这似乎行不通。 redis.GetById 始终返回 null。我做错了什么?

谢谢。

更新 1:

如果我将获取数据的行更改为:

IEnumerable<SampleEvent> events = redis.GetValue("urn:medications:25");

然后我取回我的对象​​,但即使在超时之后也应该将其删除。

最佳答案

好吧,我想我明白了。这似乎是 TypedRedisClient 和/或 key 处理方式的错误。

我会在这里发布我的解决方案,以帮助那些在这个简单场景中遇到问题的人,我想将 Redis 用作持久缓存,而不真正关心 Sets、Hashes 等的额外功能...

添加以下扩展方法:

using System;
using System.Text;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using ServiceStack.OrmLite;
using ServiceStack.Common;
using ServiceStack.Common.Utils;
using ServiceStack.DesignPatterns.Model;
using ServiceStack.ServiceInterface;
using ServiceStack.CacheAccess;
using ServiceStack.ServiceHost;
using ServiceStack.Redis;

namespace Redis.Extensions
{
    public static class RedisExtensions
    {
        internal static T GetFromCache<T>(this IRedisClient redisClient, string cacheKey,
            Func<T> factoryFn,
            TimeSpan expiresIn)
        {
            var res = redisClient.Get<T>(cacheKey);
            if (res != null)
            {
                redisClient.Set<T>(cacheKey, res, expiresIn);
                return res;
            }
            else
            {
                res = factoryFn();
                if (res != null) redisClient.Set<T>(cacheKey, res, expiresIn);
                return res;
            }
        }

    }
}

然后我将测试代码更改为此。显然这是草率的,需要改进,但至少我的测试按预期工作。

using ServiceStack.Redis;
using ServiceStack.Redis.Generic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Redis.Extensions;

namespace RedisTestsWithBooksleeve.Controllers
{
    public class SampleEvent
    {
        public int ID { get; set; }
        public string EntityID { get; set; }
        public string Name { get; set; }
    }

    public class ValuesController : ApiController
    {
        public IEnumerable<string> Get()
        {
            using (var redisClient = new RedisClient("localhost"))
            {
                if (!redisClient.ContainsKey("Meds25"))
                {

                    redisClient.GetFromCache<IEnumerable<SampleEvent>>("Meds25", () => { 

                        var medsWithID25 = new List<SampleEvent>();
                        medsWithID25.Add(new SampleEvent() { ID = 1, EntityID = "25", Name = "Digoxin" });
                        medsWithID25.Add(new SampleEvent() { ID = 2, EntityID = "25", Name = "Aspirin" });

                        return medsWithID25;

                    }, TimeSpan.FromSeconds(5));
                }

            }

            return new string[] { "1", "2" };
        }

        public SampleEvent Get(int id)
        {
            using (var redisClient = new RedisClient("localhost"))
            {
                IEnumerable<SampleEvent> events = redisClient.GetFromCache<IEnumerable<SampleEvent>>("Meds25", () =>
                {

                    var medsWithID25 = new List<SampleEvent>();
                    medsWithID25.Add(new SampleEvent() { ID = 1, EntityID = "25", Name = "Digoxin" });
                    medsWithID25.Add(new SampleEvent() { ID = 2, EntityID = "25", Name = "Aspirin" });

                    return medsWithID25;

                }, TimeSpan.FromSeconds(5));

                if (events != null)
                {
                    return events.Where(m => m.ID == id).SingleOrDefault();
                }
                else
                    return null;
            }
        }
    }
}

关于c# - ServiceStack.Redis 存储对象超时,key 检索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14551622/

有关c# - ServiceStack.Redis 存储对象超时,key 检索的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  4. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  5. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  6. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  7. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  8. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  9. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  10. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

随机推荐