복붙노트

[REDIS] 아웃 프로세스의 구현 캐시 윈도우 푸른에 레디 스를 사용하여

REDIS

아웃 프로세스의 구현 캐시 윈도우 푸른에 레디 스를 사용하여

나는 나의 푸른 구름이 데이터베이스에서 웹 페이지에 그 표시 테이블을 작업했습니다. DB를 호출을 줄이기 위해 직접 성능 향상을 위해 나는 페이지에 대한 캐시를 구축하고 싶습니다. (가) 테이블의 읽기에 대한 현재, 나는 (공정 중) 인 메모리 캐시를 누르고 있습니다. 지금은 (값이 업데이트되거나 추가 된 후 메모리 내 캐시가 더 이상 유효하지 않기 때문에) 쓰기가 삽입 또는 업데이트를 의미했다 때부터 업데이트해야합니다 아웃 - 오브 - 프로세스를 캐시를하지 않습니다 싶습니다.

나는 레디 스에 추천되었다, 나는 내가 그것을 함께 독립 프로세스 캐시를 구축하고 나의 현재 프로젝트에 결합 시작하는 방법을 파악하는 데 도움이되는 몇 가지 코드 샘플을 찾을 수있는 특정 도서 슬리브, 내 질문입니다.

미리 감사드립니다

해결법

  1. ==============================

    1.그것은 완전히 안전 스레드 및 멀티플렉서로 작동합니다 - 사용자가 만든 안 / : 다음과 같은,하지만 BookSleeve 공유 할 수 있도록 설계되어 주목 - 당신이 순수하게 독립 프로세스 싶은 경우에, 그것은 매우 간단입니다 모든 통화를 폐기하십시오. 이러한 맥락에서 나는 단순히 바이트 [] API를 노출하고있어 있도록 별도로 직렬화를 처리 할 수 ​​있으리라 믿고있어 것도 참고 :

    그것은 완전히 안전 스레드 및 멀티플렉서로 작동합니다 - 사용자가 만든 안 / : 다음과 같은,하지만 BookSleeve 공유 할 수 있도록 설계되어 주목 - 당신이 순수하게 독립 프로세스 싶은 경우에, 그것은 매우 간단입니다 모든 통화를 폐기하십시오. 이러한 맥락에서 나는 단순히 바이트 [] API를 노출하고있어 있도록 별도로 직렬화를 처리 할 수 ​​있으리라 믿고있어 것도 참고 :

    class MyCache : IDisposable
    {
        public void Dispose()
        {
            var tmp = conn;
            conn = null;
            if (tmp != null)
            {
                tmp.Close(true);
                tmp.Dispose();
            }
        }
        private RedisConnection conn;
        private readonly int db;
        public MyCache(string configuration = "127.0.0.1:6379", int db = 0)
        {
            conn = ConnectionUtils.Connect(configuration);
            this.db = db;
            if (conn == null) throw new ArgumentException("It was not possible to connect to redis", "configuration");
        }
        public byte[] Get(string key)
        {
            return conn.Wait(conn.Strings.Get(db, key));
        }
        public void Set(string key, byte[] value, int timeoutSeconds = 60)
        {
            conn.Strings.Set(db, key, value, timeoutSeconds);
        }
    }
    

    지금처럼 당신은 캐시 무효화가 필요, 즉 로컬 메모리와 독립 프로세스 캐시를 사용하여 - 흥미로운를 얻을하면 2 계층 캐시를 원하는 경우입니다. 펍 / 서브는 편리하게 - 다음과 같은 프로그램이 있습니다. 그것은 분명하지 않을 수도 있지만,이 (당신이보고 모니터를 사용할 수 있습니다) 레디 스에 많은 적은 통화를하고있을 것입니다 - 대부분의 요청이 로컬 캐시에서 처리하기 때문이다.

    using BookSleeve;
    using System;
    using System.Runtime.Caching;
    using System.Text;
    using System.Threading;
    
    class MyCache : IDisposable
    {
        public void Dispose()
        {
            var tmp0 = conn;
            conn = null;
            if (tmp0 != null)
            {
                tmp0.Close(true);
                tmp0.Dispose();
            }
    
            var tmp1 = localCache;
            localCache = null;
            if (tmp1 != null)
                tmp1.Dispose();
    
            var tmp2 = sub;
            sub = null;
            if (tmp2 != null)
            {
                tmp2.Close(true);
                tmp2.Dispose();
            }
    
        }
        private RedisSubscriberConnection sub;
        private RedisConnection conn;
        private readonly int db;
        private MemoryCache localCache;
        private readonly string cacheInvalidationChannel;
        public MyCache(string configuration = "127.0.0.1:6379", int db = 0)
        {
            conn = ConnectionUtils.Connect(configuration);
            this.db = db;
            localCache = new MemoryCache("local:" + db.ToString());
            if (conn == null) throw new ArgumentException("It was not possible to connect to redis", "configuration");
            sub = conn.GetOpenSubscriberChannel();
            cacheInvalidationChannel = db.ToString() + ":inval"; // note that pub/sub is server-wide; use
                                                                 // a channel per DB here
            sub.Subscribe(cacheInvalidationChannel, Invalidate);   
        }
    
        private void Invalidate(string channel, byte[] payload)
        {
            string key = Encoding.UTF8.GetString(payload);
            var tmp = localCache;
            if (tmp != null) tmp.Remove(key);
        }
        private static readonly object nix = new object();
        public byte[] Get(string key)
        {
            // try local, noting the "nix" sentinel value
            object found = localCache[key];
            if (found != null)
            {
                return found == nix ? null : (byte[])found;
            }
    
            // fetch and store locally
            byte[] blob = conn.Wait(conn.Strings.Get(db, key));
            localCache[key] = blob ?? nix;
            return blob;
        }
    
        public void Set(string key, byte[] value, int timeoutSeconds = 60, bool broadcastInvalidation = true)
        {
            localCache[key] = value;
            conn.Strings.Set(db, key, value, timeoutSeconds);
            if (broadcastInvalidation)
                conn.Publish(cacheInvalidationChannel, key);
        }
    }
    
    static class Program
    {
        static void ShowResult(MyCache cache0, MyCache cache1, string key, string caption)
        {
            Console.WriteLine(caption);
            byte[] blob0 = cache0.Get(key), blob1 = cache1.Get(key);
            Console.WriteLine("{0} vs {1}",
                blob0 == null ? "(null)" : Encoding.UTF8.GetString(blob0),
                blob1 == null ? "(null)" : Encoding.UTF8.GetString(blob1)
                );
        }
        public static void Main()
        {
            MyCache cache0 = new MyCache(), cache1 = new MyCache();
            string someRandomKey = "key" + new Random().Next().ToString();
            ShowResult(cache0, cache1, someRandomKey, "Initially");
            cache0.Set(someRandomKey, Encoding.UTF8.GetBytes("hello"));
            Thread.Sleep(10); // the pub/sub is fast, but not *instant*
            ShowResult(cache0, cache1, someRandomKey, "Write to 0");
            cache1.Set(someRandomKey, Encoding.UTF8.GetBytes("world"));
            Thread.Sleep(10); // the pub/sub is fast, but not *instant*
            ShowResult(cache0, cache1, someRandomKey, "Write to 1");
        }
    }
    

    전체 구현에 당신은 아마 등 약간 지연 재 연결로, 가끔 깨진 연결을 처리 할 것을 주

  2. from https://stackoverflow.com/questions/16590931/implementing-out-of-process-cache-using-redis-in-windows-azure by cc-by-sa and MIT license