예제 #1
0
 /// <summary>
 /// 在Cached的Hashtable内判断Key是否存在
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public static bool IsExitsKey(string key)
 {
     if (MC.KeyExists(key))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
예제 #2
0
 public static void Add(string key, object value, DateTime ExpireDate)
 {
     if (mc.KeyExists(key))
     {
         mc.Set(key, value, ExpireDate);
     }
     else
     {
         mc.Add(key, value, ExpireDate);
     }
 }
        public override object Get(string key)
        {
            Debug.WriteLine("Get " + key);

            InicializaMemcached();

            MemcachedClient cache = new MemcachedClient();

            string chave = MD5(key);

            if (cache.KeyExists(chave))
            {
                return cache.Get(chave);
            }
            else
            {
                return null;
            }
        }
        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            utcExpiry = TimeZoneInfo.ConvertTimeFromUtc(utcExpiry, TimeZoneInfo.Local);
            var agora = DateTime.Now;
            Debug.WriteLine("Add"+key + " __ " + utcExpiry.Subtract(agora).TotalSeconds.ToString());

            InicializaMemcached();

            MemcachedClient cache = new MemcachedClient();

            string chave = MD5(key);

            if (cache.KeyExists(chave))
            {
                return cache.Get(chave);
            }
            else
            {
                cache.Set(chave, entry, utcExpiry.ToUniversalTime());
                return entry;
            }
        }
예제 #5
0
        public void test()
        {
            //分布Memcachedf服务IP 端口
            string[] servers = { "127.0.0.1:11211" };

            //初始化池
            SockIOPool pool = SockIOPool.GetInstance();

            pool.SetServers(servers, true);
            pool.InitConnections      = 3;
            pool.MinConnections       = 3;
            pool.MaxConnections       = 5;
            pool.SocketConnectTimeout = 1000;
            pool.SocketTimeout        = 3000;
            pool.MaintenanceSleep     = 30;
            pool.Failover             = true;
            pool.Nagle = false;
            pool.Initialize();
            //客户端实例
            MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient();

            mc.EnableCompression = false;
            StringBuilder sb = new StringBuilder();

            //写入缓存
            sb.AppendLine("写入缓存测试:");
            sb.AppendLine("<br>_______________________________________<br>");
            if (mc.KeyExists("cache"))
            {
                sb.AppendLine("缓存cache已存在");
            }
            else
            {
                mc.Set("cache", "写入缓存时间:" + DateTime.Now.ToString());
                sb.AppendLine("缓存已成功写入到cache");
            }

            sb.AppendLine("<br>_______________________________________<br>");
            sb.AppendLine("读取缓存内容如下:<br>");
            sb.AppendLine(mc.Get("cache").ToString());

            //测试缓存过期
            sb.AppendLine("<br>_______________________________________<br>");
            if (mc.KeyExists("endCache"))
            {
                sb.AppendLine("缓存endCache已存在,过期时间为:" + mc.Get("endCache").ToString());
            }
            else
            {
                mc.Set("endCache", DateTime.Now.AddMinutes(1).ToString(), DateTime.Now.AddMinutes(1));
                sb.AppendLine("缓存已更新写入到endCache,写入时间:" + DateTime.Now.ToString() + " 过期时间:" + DateTime.Now.AddMinutes(1).ToString());
            }

            //分析缓存状态
            Hashtable ht = mc.Stats();

            sb.AppendLine("<br>_______________________________________<br>");
            sb.AppendLine("Memcached Stats:");
            sb.AppendLine("<br>_______________________________________<br>");
            foreach (DictionaryEntry de in ht)
            {
                Hashtable info = (Hashtable)de.Value;
                foreach (DictionaryEntry de2 in info)
                {
                    sb.AppendLine(de2.Key.ToString() + ":&nbsp;&nbsp;&nbsp;&nbsp;" + de2.Value.ToString() + "<br>");
                }
            }
            Console.WriteLine(sb.ToString());
            //Response.Write(sb.ToString());
        }
        public IAsyncResult BeginProcessRequest ( HttpContext context, AsyncCallback cb, object extraData ) {

            m_stopwatch.Start();

            FileInfo fileInfo = new FileInfo(context.Request.MapPath(context.Request.CurrentExecutionFilePath));
            this.LogDebug("File Date: {0}; File Length: {1}", fileInfo.LastWriteTimeUtc, fileInfo.Length);
            m_CONTENT_IS_MEMCACHED = false;
            m_USE_MEMCACHED = false;
            m_httpContext = context;
            m_returnOutput = true;
            m_httpMethod = m_httpContext.Request.HttpMethod;
            m_memcachedClient = (Client)context.Application["memcached"];
            m_encoding = (UTF8Encoding)context.Application["encoding"];
            m_queueClient = (QueueClient)context.Application["queueclient"];
            m_hashkey = (string)context.Application["hashkey"];
            m_xmlServiceOperationManager = (XPathServiceOperationManager)context.Application["xmlServiceOperationManager"];
            m_xslTransformationManager = (XsltTransformationManager)context.Application["xslTransformationManager"];
            m_transform = m_xslTransformationManager.Transform;
            m_xsltParams = (Hashtable)context.Application["globalXsltParams"];
            m_transformContext = new Transform.Context(context, m_hashAlgorithm, (string)context.Application["hashkey"], fileInfo, (Hashtable)m_xsltParams.Clone(), fileInfo.LastWriteTimeUtc, fileInfo.Length);
            m_namedXsltHashtable = (Hashtable)context.Application["namedXsltHashtable"];
            m_xmlSourceETagDictionary = m_xmlServiceOperationManager.XmlSourceETagDictionary;
            m_xmlReaderDictionary = m_xmlServiceOperationManager.XmlReaderDictionary;
            m_context = new Context(context, m_hashAlgorithm, m_hashkey, fileInfo, fileInfo.LastWriteTimeUtc, fileInfo.Length);
            this.LogDebug("File Date: {0}; File Length: {1}", m_context.RequestXmlFileInfo.LastWriteTimeUtc, m_context.RequestXmlFileInfo.Length);
            m_nuxleusAsyncResult = new Nuxleus.Core.NuxleusAsyncResult(cb, extraData);
            m_callback = cb;
            m_nuxleusAsyncResult.m_context = context;
            m_builder = new StringBuilder();
            m_CONTENT_IS_MEMCACHED = false;
            m_USE_MEMCACHED = (bool)context.Application["usememcached"];
            Uri requestUri = new Uri(m_context.RequestUri);
            m_requestHashcode = m_context.GetRequestHashcode(true).ToString();
            m_lastModifiedKey = String.Format("LastModified:{0}", m_context.RequestUri.GetHashCode());
            m_lastModifiedDate = String.Empty;
            m_request = new TransformRequest();
            m_response = new TransformResponse();
            Guid requestGuid = Guid.NewGuid();
            m_request.ID = requestGuid;

            
            context.Response.ContentType = "text/xml";

            IEnumerator headers = context.Request.Headers.GetEnumerator();
            for (int i = 0; headers.MoveNext(); i++) {
                string local = context.Request.Headers.AllKeys[i].ToString();
                this.LogDebug("KeyName: {0}, KeyValue: {1}", local, context.Request.Headers[local]);
            }
            bool hasXmlSourceChanged = m_xmlServiceOperationManager.HasXmlSourceChanged(m_context.RequestXmlETag, requestUri);

            //if (m_USE_MEMCACHED) {

            //    string obj = (string)m_memcachedClient.Get(m_context.GetRequestHashcode(true).ToString());

            //    if (obj != null && !hasXmlSourceChanged) {
            //        m_response.TransformResult = (string)obj;
            //        m_CONTENT_IS_MEMCACHED = true;
            //        if ((bool)context.Application["debug"]) {
            //            context.Response.ContentType = "text";
            //        }
            //    } else {
            //        //m_writer = new StringWriter(m_builder);
            //        m_CONTENT_IS_MEMCACHED = false;
            //    }
            //} else {
            //    m_writer = new StringWriter(m_builder);
            //}

            m_writer = new StringWriter(m_builder);

            try {

                switch (m_httpMethod) {
                    case "GET":
                    case "HEAD":
                    case "POST": {                     
                            string name = String.Format("Name: {0}", context.Request.QueryString["name"]);
                            this.LogDebug("QueryString Length: {0}", context.Request.QueryString.Count);
                            this.LogDebug(name);
                            this.LogDebug("If-None-Match: {0}, RequestHashCode: {1}", context.Request.Headers["If-None-Match"], m_requestHashcode);
                            this.LogDebug(context.Request.Path);
                            if (context.Request.Headers["If-None-Match"] == m_requestHashcode) {
                                this.LogDebug("They matched.");
                                this.LogDebug("Use memcached: {0}, KeyExists: {1}, XmlSource Changed: {2}", m_USE_MEMCACHED, m_memcachedClient.KeyExists(m_lastModifiedKey), hasXmlSourceChanged);
                                this.LogDebug("Last Modified Key Value: {0}", m_lastModifiedKey);
                                if (m_USE_MEMCACHED && m_memcachedClient.KeyExists(m_lastModifiedKey) && !hasXmlSourceChanged) {
                                    m_lastModifiedDate = (string)m_memcachedClient.Get(m_lastModifiedKey);
                                    this.LogDebug("Last Modified Date: {0}", m_lastModifiedDate);
                                    if (context.Request.Headers["If-Modified-Since"] == m_lastModifiedDate) {

                                        context.Response.StatusCode = 304;
                                        m_returnOutput = false;
                                        goto CompleteCall;
                                    } else {
                                        goto Process;
                                    }
                                } else if (m_CONTENT_IS_MEMCACHED) {
                                    goto CompleteCall;
                                } else {
                                    goto Process;
                                }
                            } else {
                                this.LogDebug("Headers do not match.  Beginning transformation process...");
                                m_returnOutput = true;
                                goto Process;
                            }
                        }
                    case "PUT": {
                            goto CompleteCall;
                        }
                    case "DELETE": {
                            goto CompleteCall;
                        }
                    default: {
                            goto CompleteCall;
                        }
                }

            } catch (Exception ex) {
                m_exception = ex;
                WriteError();
                goto CompleteCall;
            }
        Process:
            try {
                this.LogDebug("Processing Transformation");
                this.LogDebug("Request XML ETag Value: {0}, Request URI: {1}", m_context.RequestXmlETag, requestUri);

                XPathNavigator navigator = m_xmlServiceOperationManager.GetXPathNavigator(m_context.RequestXmlETag, requestUri);
                //if (initialReader == null) {
                //    initialReader = reader;
                //} else {
                //    this.LogDebug("XmlReaders are the same object: {0}", initialReader.Equals(reader));
                //}
                //this.LogDebug("XML Reader Value: {0}", reader.ReadOuterXml());
                //this.LogDebug("XML Reader Hash: {0}", reader.GetHashCode());
                XPathServiceOperationNavigator serviceOperationReader = new XPathServiceOperationNavigator(context, m_context, m_transformContext, navigator, m_request, m_response, m_xslTransformationManager);
                m_response = serviceOperationReader.Process();

            } catch (Exception e) {
                this.LogDebug("Error: {0} in transformation.", e.Message);
                m_exception = e;
                WriteError();
            }

            goto CompleteCall;

        CompleteCall:
            this.LogDebug("CompleteCall reached");
            if (m_lastModifiedDate == String.Empty) {
                m_lastModifiedDate = DateTime.UtcNow.ToString("r");
            }
            context.Response.AppendHeader("Cache-Control", "max-age=86400");
            context.Response.AddHeader("Last-Modified", m_lastModifiedDate);
            context.Response.AddHeader("ETag", String.Format("\"{0}\"", m_requestHashcode));
            m_nuxleusAsyncResult.CompleteCall();
            return m_nuxleusAsyncResult;
        }
예제 #7
0
        public void test()
        {
            //分布Memcachedf服务IP 端口
            string[] servers = { "192.168.3.33:11211", "192.168.202.128:11211" };

            //初始化池
            SockIOPool pool = SockIOPool.GetInstance();
            pool.SetServers(servers);
            pool.InitConnections = 3;
            pool.MinConnections = 3;
            pool.MaxConnections = 5;
            pool.SocketConnectTimeout = 1000;
            pool.SocketTimeout = 3000;
            pool.MaintenanceSleep = 30;
            pool.Failover = true;
            pool.Nagle = false;
            pool.Initialize();
            //客户端实例
            MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient();
            mc.EnableCompression = false;
            StringBuilder sb = new StringBuilder();
            //写入缓存
            sb.AppendLine("写入缓存测试:");
            sb.AppendLine("<br>_______________________________________<br>");
            if (mc.KeyExists("cache"))
            {
                sb.AppendLine("缓存cache已存在");
            }
            else
            {
                mc.Set("cache", "写入缓存时间:" + DateTime.Now.ToString());
                sb.AppendLine("缓存已成功写入到cache");
            }
            sb.AppendLine("<br>_______________________________________<br>");
            sb.AppendLine("读取缓存内容如下:<br>");
            sb.AppendLine(mc.Get("cache").ToString());

            //测试缓存过期
            sb.AppendLine("<br>_______________________________________<br>");
            if (mc.KeyExists("endCache"))
            {
                sb.AppendLine("缓存endCache已存在,过期时间为:" + mc.Get("endCache").ToString());
            }
            else
            {
                mc.Set("endCache", DateTime.Now.AddMinutes(1).ToString(), DateTime.Now.AddMinutes(1));
                sb.AppendLine("缓存已更新写入到endCache,写入时间:" + DateTime.Now.ToString() + " 过期时间:" + DateTime.Now.AddMinutes(1).ToString());
            }

            //分析缓存状态
            Hashtable ht = mc.Stats();
            sb.AppendLine("<br>_______________________________________<br>");
            sb.AppendLine("Memcached Stats:");
            sb.AppendLine("<br>_______________________________________<br>");
            foreach (DictionaryEntry de in ht)
            {
                Hashtable info = (Hashtable)de.Value;
                foreach (DictionaryEntry de2 in info)
                {
                    sb.AppendLine(de2.Key.ToString() + ":&nbsp;&nbsp;&nbsp;&nbsp;" + de2.Value.ToString() + "<br>");
                }
            }
            Response.Write(sb.ToString());
        }