在RESTful WCF服务中缓存对象

时间:2011-10-04 21:39:06

标签: c# wcf caching rest

我正在寻找一种使用RESTful WCF服务在内存中缓存对象的方法。该服务完全无状态,并在IIS之外托管。我想自己实现缓存,所以memcached不是一个选项。

现在我正在考虑托管一个单独的有状态System.ServiceModel.ServiceHost来执行所有缓存。它将通过单独的端口或其他方式与其余的WCF方法进行通信。但是我不确定这是否是解决我问题的理想方案。有人有任何提示吗?

1 个答案:

答案 0 :(得分:2)

我理解你在无状态服务和有状态主机之间的混淆以及两者如何互动。

在这个代码示例中,我概念性地演示了内存单例(缓存机制,我以后称为CachingProvider)如何可以被服务类(服务实例在生命周期中更精确地引用)引用请求)和服务主机(在这种情况下,我选择它作为控制台应用程序

我假设这里,服务接口和类都位于托管服务的控制台应用程序项目中。

在这个简单的例子中,我的原始CachingProvider类基本上充当了对GetData方法进行多少服务调用的计数器,服务主机将每5秒轮询一次CachingProvider以获取到目前为止的服务电话数量。

注意:您可以使用WCFTestClient实用程序快速测试。

免责声明: 我绝不建议像本示例中那样简单地实现复杂的缓存机制,此代码仅用于演示目的。

namespace ServiceHostConsole
{
    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        string GetData(int value);
    }

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class TestService : ITestService
    {
        public TestService()
        {
            CachingProvider.CallCount++;
        }

        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }
    }

    //For demonstration purposes only
    static class CachingProvider
    {
        static CachingProvider()
        {
            //private static constructor can initialize 
            //static cacheable resources
            _callCounter = 0; //Trivial example of initialization
        }

        private static int _callCounter;
        public static int CallCount
        {
            set { _callCounter = value; }
            get { return _callCounter; }
        }
    }

    class Program
    {
        static void Main()
        {
            using (var host = new ServiceHost(typeof(TestService), new Uri("http://localhost/TestService")))
            {
                host.Open();

                //Example how the ServiceHost can report on a persistent in-memory object that is being
                //updated each time the service is called.
                new Timer(state => Console.WriteLine("# of service calls: {0}", CachingProvider.CallCount), null, 0, 5000);

                Console.Read();
                host.Close();
            }
        }
    }
}
相关问题