Search code examples
redisservicestackormlite-servicestack

Redis caching with ServiceStack OrmLite and SQL Server persistence


We have a Web app (ASP.NET/C#) with SQL Server backend. We use ServiceStack OrmLite as our POCO Micro ORM. We would now like to extend a part of our app to cache frequently-read data (mainly a collection of POCO objects as values, with numeric keys). But I'm not sure how to go about integrating a simple caching solution (in-memory or Redis based) that works seamlessly with OrmLite and MSSQL as the Master database.

I've read about the ServiceStack Redis Client, MemoryCacheClient and Multi nested database connections (OrmLiteConnectionFactory), but I couldn't find any examples, tutorial or code samples to learn more about implementing caching that works with OrmLite.

Any suggestions or links will be helpful and much appreciated.


Solution

  • You'd need to implement the caching logic yourself, but it's not much work - here's a pseudocode example:

        public class QueryObject
        {
            public DateTime? StartDate { get; set; }
            public string SomeString { get; set; }
        }
    
        public class Foo
        {
            public DateTime DateTime { get; set; }
            public string Name { get; set; }
        }
    
        public class FooResponse
        {
            public List<Dto> Data { get; set; }
        }
    
    
        public FooResponse GetFooData(QueryObject queryObject)
        {
            using (var dbConn = connectionFactory.OpenDbConnection())
            using (var cache = redisClientsManager.GetCacheClient())
            {
                var cacheKey = string.Format("fooQuery:{0}", queryObject.GetHashCode()); //insert your own logic for generating a cache key here
                var response = cache.Get<Response>(cacheKey);
    
                //return cached result
                if (response != null) return response;
    
                //not cached - hit the DB and cache the result
                response = new FooResponse()
                    {
                        Data =
                            dbConn.Select<Foo>(
                                x => x.DateTime > queryObject.StartDate.Value && x.Name.StartsWith(queryObject.SomeString)).ToList()
                    };
                cache.Add(cacheKey, response, DateTime.Now.AddMinutes(15)); //the next time we get the same query in the next 15 mins will return cached result
                return response;
    
            }
        }