예제 #1
0
 public IDatabase GetClient(CacheEndpoint endpoint, int connectTimeout)
 {
     try
     {
         var info = endpoint as RedisEndpoint;
         Check.NotNull(info, "endpoint");
         var key = string.Format("{0}{1}{2}{3}", info.Host, info.Port, info.Password, info.DbIndex);
         if (!_pool.ContainsKey(key))
         {
             var objectPool = new ObjectPool <IDatabase>(() =>
             {
                 var point       = string.Format("{0}:{1}", info.Host, info.Port);
                 var redisClient = ConnectionMultiplexer.Connect(new ConfigurationOptions()
                 {
                     EndPoints      = { { point } },
                     ServiceName    = point,
                     Password       = info.Password,
                     ConnectTimeout = connectTimeout
                 });
                 return(redisClient.GetDatabase(info.DbIndex));
             }, info.MinSize, info.MaxSize);
             _pool.GetOrAdd(key, objectPool);
             return(objectPool.GetObject());
         }
         else
         {
             return(_pool[key].GetObject());
         }
     }
     catch (Exception e)
     {
         throw new CacheException(e.Message);
     }
 }
예제 #2
0
 public CouchbaseClient GetClient(CacheEndpoint endpoint, int connectTimeout)
 {
     lock (Clients)
     {
         try
         {
             var info = endpoint as CouchBaseEndpoint;
             Check.NotNull(info, "endpoint");
             var key = string.Format("{0}{1}{2}{3}{4}", info.Host, info.Port, info.BucketName, info.BucketPassword, info.Db);
             if (!Clients.ContainsKey(key))
             {
                 var clientConfiguration = new CouchbaseClientConfiguration();
                 var url = new Uri(string.Format("http://{0}:{1}/{2}", info.Host, info.Port, info.Db));
                 clientConfiguration.Bucket         = info.BucketName;
                 clientConfiguration.BucketPassword = info.BucketPassword;
                 clientConfiguration.Urls.Add(url);
                 clientConfiguration.HttpRequestTimeout     = TimeSpan.FromSeconds(connectTimeout);
                 clientConfiguration.SocketPool.MaxPoolSize = info.MaxSize;
                 clientConfiguration.SocketPool.MinPoolSize = info.MinSize;
                 var couchbaseClient = new CouchbaseClient(clientConfiguration);
                 Clients.GetOrAdd(key, couchbaseClient);
                 return(couchbaseClient);
             }
             else
             {
                 return(Clients[key]);
             }
         }
         catch (Exception)
         {
             return(null);
         }
     }
 }
예제 #3
0
 public IRedisClient GetClient(CacheEndpoint endpoint, int connectTimeout)
 {
     try
     {
         var info = endpoint as RedisEndpoint;
         Check.NotNull(info, "endpoint");
         var key = string.Format("{0}{1}{2}{3}", info.Host, info.Port, info.Password, info.DbIndex);
         if (!_pool.ContainsKey(key))
         {
             var objectPool = new ObjectPool <IRedisClient>(() =>
             {
                 var redisClient            = new RedisClient(info.Host, info.Port, info.Password, info.DbIndex);
                 redisClient.ConnectTimeout = connectTimeout;
                 return(redisClient);
             }, info.MinSize, info.MaxSize);
             _pool.GetOrAdd(key, objectPool);
             return(objectPool.GetObject());
         }
         else
         {
             return(_pool[key].GetObject());
         }
     }
     catch (Exception e)
     {
         throw new CacheException(e.Message);
     }
 }
예제 #4
0
        public async Task <bool> ConnectionAsync(CacheEndpoint endpoint)
        {
            var connection = await _cacheClient
                             .Value.ConnectionAsync(endpoint, ConnectTimeout);

            return(connection);
        }
        public async Task <bool> ConnectionAsync(CacheEndpoint endpoint, int connectTimeout)
        {
            ConnectionMultiplexer conn = null;

            try
            {
                var info  = endpoint as ConsistentHashNode;
                var point = string.Format("{0}:{1}", info.Host, info.Port);
                conn = await ConnectionMultiplexer.ConnectAsync(new ConfigurationOptions()
                {
                    EndPoints      = { { point } },
                    ServiceName    = point,
                    Password       = info.Password,
                    ConnectTimeout = connectTimeout
                });

                return(conn.IsConnected);
            }
            catch (Exception e)
            {
                throw new CacheException(e.Message);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
            }
        }
예제 #6
0
 public Task MarkFailure(CacheEndpoint address, string cacheId)
 {
     return(Task.Run(() =>
     {
         var entry = _dictionary.GetOrAdd(new ValueTuple <string, int>(address.Host, address.Port), k => new MonitorEntry(address, cacheId, false));
         entry.Health = false;
     }));
 }
예제 #7
0
        /// <summary>
        /// 判断一个地址是否健康。
        /// </summary>
        /// <param name="address">地址模型。</param>
        /// <param name="cacheId">The cache identifier.</param>
        /// <returns>健康返回true,否则返回false。</returns>
        public ValueTask <bool> IsHealth(CacheEndpoint address, string cacheId)
        {
            MonitorEntry entry;

            return(!_dictionary.TryGetValue(new ValueTuple <string, int>(address.Host, address.Port), out entry)
                ? new ValueTask <bool>(Check(address, cacheId))
                : new ValueTask <bool>(entry.Health));
        }
예제 #8
0
        public async Task <bool> ConnectionAsync(CacheEndpoint endpoint)
        {
            try
            {
                var timeSpan = await _cacheClient.Value.GetClient(endpoint, ConnectTimeout).PingAsync();

                return(true);
            } catch
            {
                return(false);
            }
        }
예제 #9
0
        /// <summary>
        /// Clears cache server with given clear criteria
        /// </summary>
        /// <param name="criteria">A query to filter cache keys, works with redis search characters</param>
        public void ClearCache(CacheClearQuery criteria)
        {
            var db = CacheEndpoint.GetDatabase();

            foreach (var endPoint in CacheEndpoint.GetEndPoints())
            {
                var server = CacheEndpoint.GetServer(endPoint);

                foreach (var redisKey in server.Keys(pattern: criteria.Pattern))
                {
                    Delete(db, new CacheKey(redisKey));
                }
            }
        }
예제 #10
0
 public ConnectionMultiplexer Connection(CacheEndpoint endpoint, int connectTimeout)
 {
     try
     {
         var info  = endpoint as RedisEndpoint;
         var point = string.Format("{0}:{1}", info.Host, info.Port);
         return(ConnectionMultiplexer.Connect(new ConfigurationOptions()
         {
             EndPoints = { { point } },
             ServiceName = point,
             Password = info.Password,
             ConnectTimeout = connectTimeout
         }));
     }
     catch (Exception e)
     {
         throw new CacheException(e.Message);
     }
 }
예제 #11
0
        /// <summary>Determines whether the specified object is equal to the current object.</summary>
        /// <returns>true if the specified object  is equal to the current object; otherwise, false.</returns>
        /// <param name="obj">The object to compare with the current object. </param>
        public override bool Equals(object obj)
        {
            var model = obj as ServiceCache;

            if (model == null)
            {
                return(false);
            }

            if (obj.GetType() != GetType())
            {
                return(false);
            }

            if (model.CacheDescriptor != CacheDescriptor)
            {
                return(false);
            }

            return(model.CacheEndpoint.Count() == CacheEndpoint.Count() && model.CacheEndpoint.All(addressModel => CacheEndpoint.Contains(addressModel)));
        }
 public IServer GetServer(CacheEndpoint endpoint, int connectTimeout)
 {
     try
     {
         var info = endpoint as RedisEndpoint;
         Check.NotNull(info, "endpoint");
         var key         = string.Format("{0}{1}{2}{3}", info.Host, info.Port, info.Password, info.DbIndex);
         var point       = string.Format("{0}:{1}", info.Host, info.Port);
         var redisClient = ConnectionMultiplexer.Connect(new ConfigurationOptions()
         {
             EndPoints          = { { point } },
             ServiceName        = point,
             Password           = info.Password,
             ConnectTimeout     = connectTimeout,
             AbortOnConnectFail = false
         });
         return(redisClient.GetServer(info.Host, info.Port));
     }
     catch (Exception e)
     {
         throw new CacheException(e.Message);
     }
 }
예제 #13
0
        public CacheValue Get(CacheKey cacheKey)
        {
            var db = CacheEndpoint.GetDatabase();

            return(new CacheValue(db.StringGet(cacheKey.ToString())));
        }
예제 #14
0
        public void Delete(CacheKey cacheKey)
        {
            var db = CacheEndpoint.GetDatabase();

            db.KeyDelete(cacheKey.ToString());
        }
예제 #15
0
 private IDatabase GetRedisClient(CacheEndpoint info)
 {
     return
         (_cacheClient.Value
          .GetClient(info, ConnectTimeout));
 }
예제 #16
0
 private async Task <bool> Check(CacheEndpoint address, string id)
 {
     return(await CacheContainer.GetService <ICacheProvider>(id)
            .ConnectionAsync(address));
 }
예제 #17
0
 public void Monitor(CacheEndpoint address, string cacheId)
 {
     _dictionary.GetOrAdd(new ValueTuple <string, int>(address.Host, address.Port), k => new MonitorEntry(address, cacheId));
 }
예제 #18
0
 public bool Connection(CacheEndpoint endpoint)
 {
     return(true);
 }
예제 #19
0
 public MonitorEntry(CacheEndpoint address, string cacheId, bool health = true)
 {
     EndPoint = address;
     Health   = health;
     CacheId  = cacheId;
 }
예제 #20
0
 private IRedisClient GetRedisClient(CacheEndpoint info)
 {
     return
         (CacheContainer.GetInstances <ICacheClient <IRedisClient> >(CacheTargetType.Redis.ToString())
          .GetClient(info, ConnectTimeout));
 }
        public async Task <bool> IsHealth(CacheEndpoint address, string cacheId)
        {
            MonitorEntry entry;

            return(!_dictionary.TryGetValue(new Tuple <string, int>(address.Host, address.Port), out entry) ?  await Check(address, cacheId) : entry.Health);
        }
예제 #22
0
 private IServer GetRedisServer(CacheEndpoint info)
 {
     return
         (_cacheServer.Value
          .GetServer(info, ConnectTimeout));
 }
예제 #23
0
        public void Set(CacheKey cacheKey, CacheValue cacheObj, CacheRule cacheRule)
        {
            var db = CacheEndpoint.GetDatabase();

            db.StringSet(cacheKey.ToString(), cacheObj.Value, cacheRule.ExpiresIn);
        }
예제 #24
0
 public bool Connection(CacheEndpoint endpoint)
 {
     return(CacheContainer.GetInstances <ICacheClient <IDatabase> >(CacheTargetType.Redis.ToString())
            .Connection(endpoint, ConnectTimeout).IsConnected);
 }
예제 #25
0
 public Task <bool> ConnectionAsync(CacheEndpoint endpoint)
 {
     return(Task.FromResult <bool>(true));
 }
예제 #26
0
        public async Task SetCacheEndpointByEndpoint(string cacheId, string endpoint, CacheEndpoint cacheEndpoint)
        {
            var model = await ServiceLocator.GetService <IServiceCacheManager>().GetAsync(cacheId);

            var cacheEndpoints = model.CacheEndpoint.Where(p => p.ToString() != cacheEndpoint.ToString()).ToList();

            cacheEndpoints.Add(cacheEndpoint);
            model.CacheEndpoint = cacheEndpoints;
            var caches      = new ServiceCache[] { model };
            var descriptors = caches.Where(cache => cache != null).Select(cache => new ServiceCacheDescriptor
            {
                AddressDescriptors = cache.CacheEndpoint?.Select(address => new CacheEndpointDescriptor
                {
                    Type  = address.GetType().FullName,
                    Value = _serializer.Serialize(address)
                }) ?? Enumerable.Empty <CacheEndpointDescriptor>(),
                CacheDescriptor = cache.CacheDescriptor
            });
            await ServiceLocator.GetService <IServiceCacheManager>().SetCachesAsync(descriptors);
        }