Beispiel #1
0
        public static void Run()
        {
            var cacheClient = new CacheClient();

            // 502 chars = 1 kb
            string value = "asdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasas";

            Console.WriteLine("***** BEGIN INFINITE ADD TEST (WILL NEVER END) *****");
            Console.WriteLine();

            cacheClient.HostDisconnected += (sender, e) => { Console.WriteLine("*** Host disconnected"); };
            cacheClient.HostReconnected += (sender, e) => { Console.WriteLine("*** Host reconnected"); };

            // Add test1 to test1000
            int i = 1;
            while (true)
            {
                cacheClient.AddOrUpdate("test" + i, value);
                i++;
                if (i == 1001)
                {
                    i = 1;
                }
            }
        }
        protected override void BeginProcessing()
        {
            if (CacheKeyPrefix == null)
                CacheKeyPrefix = string.Empty;
            base.BeginProcessing();

            cacheClient = new CacheClient(ConnectionString, CacheKeyPrefix, SchemaName);
        }
Beispiel #3
0
        public static void Run()
        {
            var cacheClient = new CacheClient();

            Console.WriteLine("***** BEGIN CACHE MISS TEST *****");
            Console.WriteLine();

            cacheClient.HostDisconnected += (sender, e) => { Console.WriteLine("*** Host disconnected"); };
            cacheClient.HostReconnected += (sender, e) => { Console.WriteLine("*** Host reconnected"); };

            // Try and get 10 items
            string value = null;
            for (int i = 0; i < 10; i++)
            {
                var cacheKey = "doesNotExist" + i;
                var result = cacheClient.TryGet(cacheKey, out value);
                if (!result)
                {
                    Console.WriteLine("PASS: Did not receive value for cache key: {0}", cacheKey);
                }
                else
                {
                    Console.WriteLine("FAIL: Received value for cache key: {0}", cacheKey);
                }
            }

            // Bulk 10
            var bulkResult = cacheClient.Get<string>(new[] { "doesNotExist0", "doesNotExist1", "doesNotExist2", "doesNotExist3", "doesNotExist4",
                "doesNotExist5", "doesNotExist6", "doesNotExist7", "doesNotExist8", "doesNotExist9" });

            if (bulkResult == null)
            {
                Console.WriteLine("PASS: Did not receive values for bulk cache keys");
            }
            else
            {
                Console.WriteLine("FAIL: Received values for bulk cache keys");
            }

            // Tag
            var tagResult = cacheClient.GetTagged<string>("tagDoesntExist");
            if (tagResult == null)
            {
                Console.WriteLine("PASS: Did not receive values for tag cache keys");
            }
            else
            {
                Console.WriteLine("FAIL: Received values for tag cache keys");
            }

            var key = Console.ReadKey();
            // Graceful shutdown option
            if (key.KeyChar == 'q')
            {
                cacheClient.Shutdown();
            }
        }
        public override void ExecuteCmdlet()
        {
            Utility.ValidateResourceGroupAndResourceName(ResourceGroupName, Name);
            if (!string.IsNullOrEmpty(MaxMemoryPolicy))
            {
                throw new ArgumentException(Resources.MaxMemoryPolicyException);
            }

            RedisResource response = CacheClient.GetCache(ResourceGroupName, Name);

            string skuName;
            string skuFamily;
            int    skuCapacity;

            if (string.IsNullOrEmpty(Sku))
            {
                skuName = response.Sku.Name;
            }
            else
            {
                skuName = Sku;
            }

            if (string.IsNullOrEmpty(Size))
            {
                skuFamily   = response.Sku.Family;
                skuCapacity = response.Sku.Capacity;
            }
            else
            {
                Size      = SizeConverter.GetSizeInRedisSpecificFormat(Size, SkuStrings.Premium.Equals(Sku));
                skuFamily = Size.Substring(0, 1);
                int.TryParse(Size.Substring(1), out skuCapacity);
            }

            if (!ShardCount.HasValue && response.ShardCount.HasValue)
            {
                ShardCount = response.ShardCount;
            }


            WriteObject(new RedisCacheAttributesWithAccessKeys(
                            CacheClient.CreateOrUpdateCache(ResourceGroupName, Name, response.Location, skuFamily, skuCapacity, skuName, RedisConfiguration, EnableNonSslPort,
                                                            TenantSettings, ShardCount, response.SubnetId, response.StaticIP, response.Tags),
                            ResourceGroupName));
        }
Beispiel #5
0
        public override void ExecuteCmdlet()
        {
            Utility.ValidateResourceGroupAndResourceName(ResourceGroupName, Name);
            IList <ScheduleEntry>  response    = CacheClient.GetPatchSchedules(ResourceGroupName, Name);
            List <PSScheduleEntry> returnValue = new List <PSScheduleEntry>();

            foreach (var schedule in response)
            {
                returnValue.Add(new PSScheduleEntry
                {
                    DayOfWeek         = schedule.DayOfWeek,
                    StartHourUtc      = schedule.StartHourUtc,
                    MaintenanceWindow = schedule.MaintenanceWindow
                });
            }
            WriteObject(returnValue);
        }
        public override void ExecuteCmdlet()
        {
            Utility.ValidateResourceGroupAndResourceName(ResourceGroupName, Name);
            ResourceGroupName = CacheClient.GetResourceGroupNameIfNotProvided(ResourceGroupName, Name);

            ConfirmAction(
                string.Format(Resources.RemovePatchSchedule, Name),
                Name,
                () =>
            {
                CacheClient.RemovePatchSchedules(ResourceGroupName, Name);
                if (PassThru)
                {
                    WriteObject(true);
                }
            });
        }
 public override void ExecuteCmdlet()
 {
     Utility.ValidateResourceGroupAndResourceName(ResourceGroupName, Name);
     ConfirmAction(
         Force.IsPresent,
         string.Format(Resources.RemovingRedisCache, Name),
         string.Format(Resources.RemoveRedisCache, Name),
         Name,
         () =>
     {
         CacheClient.DeleteCache(ResourceGroupName, Name);
         if (PassThru)
         {
             WriteObject(true);
         }
     });
 }
Beispiel #8
0
 /// <summary>
 /// 刷新产品标签缓存
 /// </summary>
 /// <param name="tag"></param>
 /// <param name="pids"></param>
 /// <returns></returns>
 public bool SetProductCommonTagDetailsCache(ProductCommonTag tag, List <string> pids)
 {
     try
     {
         using (var client = new CacheClient())
         {
             var cacheResult = client.SetProductCommonTagDetailsCache(tag, pids);
             cacheResult.ThrowIfException(true);
             return(cacheResult.Result);
         }
     }
     catch (Exception ex)
     {
         _logger.Error($"{tag} 刷新标签失败 -> {string.Join(",", pids)}", ex);
         return(false);
     }
 }
Beispiel #9
0
 public ActionResult ExamActivity(Guid aid)
 {
     try
     {
         var result = QiangGouManager.ExamActivity(aid);
         if (result > 0)
         {
             var del = SeckillManager.DeleteStatusData(aid.ToString());
             if (del > 0)
             {
                 result = 1;
             }
         }
         if (result > 0)
         {
             using (var client = new CacheClient())
             {
                 var cacheresult = client.RefreshRedisCachePrefixForCommon(new RefreshCachePrefixRequest()
                 {
                     Prefix     = "SecondKillPrefix",
                     ClientName = "FlashSale",
                     Expiration = TimeSpan.FromDays(1)
                 });
                 cacheresult.ThrowIfException(true);
             }
             var cache = QiangGouManager.ReflashQiangGouCache(aid, false, 1);
             if (cache == false)
             {
                 return(Json(new { Status = 0, Message = "刷新缓存失败【请手动刷新】" }));
             }
             SeckillManager.OpertionLogs(SeckillManager.OpertionType.ApprovePass, "", "", aid.ToString());
         }
         return(Json(new
         {
             code = result
         }));
     }
     catch (Exception e)
     {
         return(Json(new
         {
             code = -3,
             msg = e.Message + e.InnerException + e.StackTrace
         }));
     }
 }
Beispiel #10
0
 /// <summary>
 /// 刷新赠品缓存
 /// </summary>
 /// <returns></returns>
 public bool RefreshGiftCache()
 {
     try
     {
         using (var client = new CacheClient())
         {
             var cacheResult = client.RefreshGiftCache();
             cacheResult.ThrowIfException(true);
             return(cacheResult.Result);
         }
     }
     catch (Exception ex)
     {
         _logger.Error("刷新赠品缓存失败", ex);
         return(false);
     }
 }
        public override void ExecuteCmdlet()
        {
            cacheServiceName = CacheClient.NormalizeCacheServiceName(Name);

            CacheClient.ProgressRecorder = (p) => { WriteVerbose(p); };

            string memory = memoryDynamicParameterSet.GetMemoryValue(Sku);

            PSCacheService cacheService = new PSCacheService(CacheClient.CreateCacheService(
                                                                 CurrentContext.Subscription.Id.ToString(),
                                                                 cacheServiceName,
                                                                 Location,
                                                                 Sku,
                                                                 memory));

            WriteObject(cacheService);
        }
        public override void ExecuteCmdlet()
        {
            Utility.ValidateResourceGroupAndResourceName(ResourceGroupName, Name);
            ResourceGroupName = CacheClient.GetResourceGroupNameIfNotProvided(ResourceGroupName, Name);

            ConfirmAction(
                string.Format(Resources.ExportRedisCache, Name),
                Name,
                () =>
            {
                CacheClient.ExportToCache(ResourceGroupName, Name, Container, Prefix, Format);
                if (PassThru)
                {
                    WriteObject(true);
                }
            });
        }
        public override void ExecuteCmdlet()
        {
            Utility.ValidateResourceGroupAndResourceName(ResourceGroupName, Name);
            ResourceGroupName = CacheClient.GetResourceGroupNameIfNotProvided(ResourceGroupName, Name);

            ConfirmAction(
                Force.IsPresent,
                string.Format(Resources.RebootingRedisCache, Name, RebootType),
                string.Format(Resources.RebootRedisCache, Name),
                Name,
                () => CacheClient.RebootCache(ResourceGroupName, Name, RebootType, ShardId));

            if (PassThru)
            {
                WriteObject(true);
            }
        }
Beispiel #14
0
        public static void Run()
        {
            var cacheClient = new CacheClient();

            // 502 chars = ~1 kb
            string value = "asdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasas";

            int itemsToAdd = 1000;

            Console.WriteLine("***** BEGIN INFINITE ADD " + itemsToAdd + " 1 KB STRING OBJECTS TEST (WILL NEVER END) *****");
            Console.WriteLine();

            cacheClient.HostDisconnected += (sender, e) => { Console.WriteLine("*** Host disconnected"); };
            cacheClient.HostReconnected += (sender, e) => { Console.WriteLine("*** Host reconnected"); };

            // Add items
            Task.Factory.StartNew(() => {
                int i = 0;
                while (true)
                {
                    try
                    {
                        cacheClient.AddOrUpdate("test" + i, value);
                    }
                    catch (NoCacheHostsAvailableException)
                    {
                        Thread.Sleep(1000);
                        continue;
                    }

                    i++;
                    if (i == itemsToAdd)
                    {
                        i = 0;
                    }
                }
            });

            var key = Console.ReadKey();
            // Graceful shutdown option
            if (key.KeyChar == 'q')
            {
                cacheClient.Shutdown();
            }
        }
Beispiel #15
0
        public Client(ClientOptions clientOptions)
        {
            EventHandler = new EventHandler(this);
            Cache        = new CacheClient(clientOptions.RedisPrefix);

            Token           = clientOptions.Token;
            BrokerUri       = clientOptions.BrokerUri;
            RedisUri        = clientOptions.RedisUri;
            Broker          = new AmqpBroker(clientOptions.BrokerName);
            Rest            = null !;
            Broker.Receive += (sender, args) =>
            {
                EventHandler.HandleEvent((SkyraEvent)Enum.Parse(typeof(SkyraEvent), args.Event), args);
                Broker.Ack(args.Event, args.DeliveryTag);
            };

            var provider = new ServiceCollection()
                           .AddSingleton(this)
                           .BuildServiceProvider();

            Events = Assembly.GetExecutingAssembly()
                     .ExportedTypes
                     .Where(type => type.GetCustomAttribute <EventAttribute>() != null)
                     .Select(type => ActivatorUtilities.CreateInstance(provider, type))
                     .Select(ToEventInfo).ToDictionary(x => x.Name, x => x);

            Monitors = Assembly.GetExecutingAssembly()
                       .ExportedTypes
                       .Where(type => type.GetCustomAttribute <MonitorAttribute>() != null)
                       .Select(type => ActivatorUtilities.CreateInstance(provider, type))
                       .Select(ToMonitorInfo).ToDictionary(x => x.Name, x => x);

            Resolvers = Assembly.GetExecutingAssembly()
                        .ExportedTypes
                        .Where(type => type.GetCustomAttribute <ResolverAttribute>() != null)
                        .Select(type => ActivatorUtilities.CreateInstance(provider, type))
                        .Select(ToArgumentInfo)
                        .ToDictionary(x => x.Type, x => x);

            Commands = Assembly.GetExecutingAssembly()
                       .ExportedTypes
                       .Where(type => type.GetCustomAttribute <CommandAttribute>() != null)
                       .Select(type => ActivatorUtilities.CreateInstance(provider, type))
                       .Select(ToCommandInfo).ToDictionary(x => x.Name, x => x);
        }
        public async static Task Run()
        {
            // =========================================================
            // Iron.io Cache
            // =========================================================

            IronCacheRestClient ironCacheClient = Client.New();

            // Get a Cache object
            CacheClient cache = ironCacheClient.Cache("my_cache");

            // Put value to cache by key
            await cache.Put("number_item", 42);

            CacheItem item = await cache.Get("number_item");

            // Get value from cache by key
            Console.WriteLine(item.Value);

            // Get value from cache by key
            Console.WriteLine(await cache.Get <int>("number_item"));

            // Numbers can be incremented
            await cache.Increment("number_item", 10);

            // Immediately delete an item
            await cache.Delete("number_item");

            await cache.Put("complex_item", new { greeting = "Hello", target = "world" });

            CacheItem complexItem = await cache.Get("complex_item");

            // Get value from cache by key
            Console.WriteLine(complexItem.Value);

            await cache.Delete("complex_item");

            await cache.Put("sample_class", new SampleClass { Name = "Sample Class CacheItem" });

            SampleClass sampleClassItem = await cache.Get <SampleClass>("sample_class");

            Console.WriteLine(sampleClassItem.Inspect());

            await cache.Delete("sample_class");
        }
        public override void ExecuteCmdlet()
        {
            if (string.IsNullOrEmpty(ExpiryPolicy))
            {
                ExpiryPolicy = _DefaultExpiryPolicy;
            }

            if (ExpiryTime == null)
            {
                ExpiryTime = _DefaultExpiryTime;
            }

            string cacheServiceName = CacheClient.NormalizeCacheServiceName(Name);

            CacheClient.ProgressRecorder = (p) => { WriteVerbose(p); };
            WriteObject(new PSCacheServiceWithNamedCaches(CacheClient.AddNamedCache(cacheServiceName, NamedCache, ExpiryPolicy, (int)ExpiryTime,
                                                                                    WithoutEviction.IsPresent, WithNotifications.IsPresent, WithHighAvailability.IsPresent)));
        }
Beispiel #18
0
 public Session this[Guid sessionId] {
     get {
         Console.WriteLine("UserSession get CacheClient: '{0}'", CacheClient);
         var authSession = CacheClient.Get <Session>(Session.ToCacheKey(sessionId));
         if (authSession != default(Session))
         {
             authSession.SetRedisClient((CacheClient as IRedisClientsManager).GetClient());
         }
         return(authSession);
     }
     set {
         if (sessionId != value.Id)
         {
             throw new Exception(string.Format("sessionId {0}!={1} value.Id ", sessionId, value.Id));
         }
         CacheClient.Replace <Session>(Session.ToCacheKey(sessionId), value, value.ExpiresAt);
     }
 }
Beispiel #19
0
        public override void ExecuteCmdlet()
        {
            RedisCacheAttributes cache = new RedisCacheAttributes(CacheClient.GetCache(ResourceGroupName, Name), ResourceGroupName);

            if (!Force.IsPresent)
            {
                ConfirmAction(
                    Force.IsPresent,
                    string.Format(Resources.RemovingRedisCacheDiagnostics, Name),
                    string.Format(Resources.RemoveRedisCacheDiagnostics, Name),
                    Name,
                    () => CacheClient.SetDiagnostics(cache.Id, null));
            }
            else
            {
                CacheClient.SetDiagnostics(cache.Id, null);
            }
        }
 public override void ExecuteCmdlet()
 {
     ConfirmAction(
         Force.IsPresent,
         string.Format(Properties.Resources.RemoveServiceWarning, Name),
         Properties.Resources.RemoveServiceMessage,
         Name,
         () =>
     {
         WriteVerbose(Properties.Resources.CacheServiceRemoveStarted);
         CacheClient.DeleteCacheService(Name);
         WriteVerbose(string.Format(Properties.Resources.CacheServiceRemoved, Name));
         if (PassThru)
         {
             WriteObject(true);
         }
     });
 }
        public override void ExecuteCmdlet()
        {
            Utility.ValidateResourceGroupAndResourceName(null, PrimaryServerName);
            Utility.ValidateResourceGroupAndResourceName(null, SecondaryServerName);
            string resourceGroupName = CacheClient.GetResourceGroupNameIfNotProvided(null, PrimaryServerName);

            ConfirmAction(
                string.Format(Resources.RemoveLinkedServer, SecondaryServerName, PrimaryServerName),
                PrimaryServerName,
                () =>
            {
                CacheClient.RemoveLinkedServer(resourceGroupName, PrimaryServerName, SecondaryServerName);
                if (PassThru)
                {
                    WriteObject(true);
                }
            });
        }
Beispiel #22
0
        public ActionResult UpdateHomePageAdvertise()
        {
            var conn = ConfigurationManager.ConnectionStrings["Gungnir"].ConnectionString;

            if (SecurityHelp.IsBase64Formatted(conn))
            {
                conn = SecurityHelp.DecryptAES(conn);
            }
            using (var dbhelper = new SqlDbHelper(conn))
            {
                var HomePageAdvertise = WebSiteHomeAdManager.SelectAllAdDetail("Home_");
            }
            using (var client = new CacheClient())
            {
                var result = client.RefreshHomePageAdvertiseCache();
                return(Json(result.Result));
            }
        }
Beispiel #23
0
        static void Test1()
        {
            var client = new CacheClient();

            client.SetServer("tcp://127.0.0.1:1234");

            //client.Bench();

            client.Set("aa", 1234);
            client.Set("bb", false);
            client.Set("cc", 3.14);
            client.Set("dd", "NewLife", 5);
            client.Set("ee", new { Name = "新生命", Year = 2002 });

            Console.WriteLine(client.Get <Int32>("aa"));
            Console.WriteLine(client.Get <Boolean>("bb"));
            Console.WriteLine(client.Get <Double>("cc"));
            Console.WriteLine(client.Get <String>("dd"));
            Console.WriteLine(client.Get <Object>("ee").ToJson());

            Console.WriteLine();
            Console.WriteLine("Count={0}", client.Count);
            Console.WriteLine("Keys={0}", client.Keys.Join());
            Thread.Sleep(2000);
            Console.WriteLine("Expire={0}", client.GetExpire("dd"));

            Console.WriteLine();
            client.Decrement("aa", 30);
            client.Increment("cc", 0.3);

            Console.WriteLine();
            var dic = client.GetAll <Object>(new[] { "aa", "cc", "ee" });

            foreach (var item in dic)
            {
                var val = item.Value;
                if (val != null && item.Value.GetType().GetTypeCode() == TypeCode.Object)
                {
                    val = val.ToJson();
                }

                Console.WriteLine("{0}={1}", item.Key, val);
            }
        }
Beispiel #24
0
        public void Remove(Guid sessionId)
        {
            Console.WriteLine("AuthUserSession.Remove:{0} - cacheKey ", Session.ToCacheKey(sessionId));
            var rc = (CacheClient as IRedisClientsManager).GetClient();           //CacheClient as IRedisClient;

            Console.WriteLine("AuthUserSession.Remove:{0} redisclient ", rc);
            if (rc != null)
            {
                var keys = rc.SearchKeys(Session.SearchKeyString(sessionId));
                if (keys != null & keys.Count > 0)
                {
                    CacheClient.RemoveAll(keys);
                }
            }
            else
            {
                CacheClient.Remove(Session.ToCacheKey(sessionId));
            }
        }
Beispiel #25
0
        internal static RedirectToActionResult OnSignIn(ControllerBase controller, string authToken)
        {
            try
            {
                CacheClient cacheClient = new CacheClient(authToken);
                string      itemKey     = Constant.Cache.ItemKey.MediaProcessors;
                cacheClient.SetValue <NameValueCollection>(itemKey, null);
            }
            catch { }

            RedirectToActionResult redirectAction = null;
            string requestError = controller.Request.Form["error_description"];

            if (!string.IsNullOrEmpty(requestError) && requestError.Contains(Constant.Message.UserPasswordForgotten))
            {
                redirectAction = controller.RedirectToAction("passwordreset", "account");
            }
            return(redirectAction);
        }
        public void Execute(IJobExecutionContext context)
        {
            using (var cacheClient = new CacheClient())
            {
                //刷新轮胎适配redis缓存
                var refreshTireAsync = cacheClient.RefreshTireAdpterCache(null, 1);
                if (!refreshTireAsync.Success)
                {
                    Logger?.Warn($"RefreshTireAdpterCache刷新失败:{refreshTireAsync.ErrorMessage}", refreshTireAsync.Exception);
                }
            }
            //获取所有tid
            var allTids = ProductCacheDal.SelectAllTids();

            using (var cacheClient = new CacheClient())
            {
                //清除缓存
                var baoyangAdapterTire = cacheClient.RefreshBaoYangVehicleAdpterCache(new List <int>()
                {
                }, true);

                //分批次刷新保养适配redis缓存
                allTids.Split(100).ForEach(p => {
                    var resultOne = cacheClient.RefreshBaoYangVehicleAdpterCache(p.ToList(), false);
                    if (!resultOne.Success)
                    {
                        using (var cacheClient2 = new CacheClient())
                        {
                            resultOne = cacheClient2.RefreshBaoYangVehicleAdpterCache(p.ToList(), false);
                            if (!resultOne.Success)
                            {
                                Logger?.Warn($"RefreshBaoYangVehicleAdpterCache刷新失败", resultOne.Exception);
                            }
                        }
                    }
                });
            }
            //发送刷新通知
            Logger.Info($"notification.productmatch.modify.RebuildAdpter=>{DateTime.Now}");
            TuhuNotification.SendNotification("notification.productmatch.modify", new { type = "RebuildAdpter" });

            //TuhuNotification.SendNotification("notification.productmatch.modify", new { type = "UpdateAdpter", pids=new string[] { } });
        }
Beispiel #27
0
        /// <summary>
        /// 刷新大客户活动配置缓存
        /// </summary>
        /// <param name="activityExclusiveId"></param>
        /// <returns></returns>

        public static bool RefreshRedisCacheCustomerSetting(string activityExclusiveId)
        {
            var result = false;

            try
            {
                using (var client = new CacheClient())
                {
                    var getResult = client.RefreshRedisCacheCustomerSetting(activityExclusiveId);
                    getResult.ThrowIfException(true);
                    result = getResult.Result;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            return(result);
        }
        public override void ExecuteCmdlet()
        {
            WriteWarning("Managed Cache will be retired on 11/30/2016. Please migrate to Azure Redis Cache. For more information, see http://go.microsoft.com/fwlink/?LinkID=717458");

            cacheServiceName = CacheClient.NormalizeCacheServiceName(Name);

            CacheClient.ProgressRecorder = (p) => { WriteVerbose(p); };

            string memory = memoryDynamicParameterSet.GetMemoryValue(Sku);

            PSCacheService cacheService = new PSCacheService(CacheClient.CreateCacheService(
                                                                 Profile.Context.Subscription.Id.ToString(),
                                                                 cacheServiceName,
                                                                 Location,
                                                                 Sku,
                                                                 memory));

            WriteObject(cacheService);
        }
Beispiel #29
0
        public static void Run()
        {
            int totalCallbacks = 0;
            var cacheClient    = new CacheClient();

            // 502 chars = ~1 kb
            string value = "asdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasas";

            int itemsToAdd = 10;
            var pause      = 2000;

            Console.WriteLine("***** BEGIN REMOVED ITEM CALLBACK TEST *****");
            Console.WriteLine();

            cacheClient.HostDisconnected += (sender, e) => { Console.WriteLine("*** Host disconnected"); };
            cacheClient.HostReconnected  += (sender, e) => { Console.WriteLine("*** Host reconnected"); };
            cacheClient.CacheItemExpired += (sender, e) => { Interlocked.Increment(ref totalCallbacks); Console.WriteLine(string.Format("Cache key expired: {0}, Total Removed: {1}", e.CacheKey, totalCallbacks)); };

            // Add items
            for (int i = 1; i <= itemsToAdd; i++)
            {
                cacheClient.AddOrUpdate("test" + i, value, notifyRemoved: true);
            }

            Console.WriteLine("***** " + itemsToAdd + " ITEMS ADDED *****");
            Console.WriteLine("***** BEGIN REMOVING " + itemsToAdd + " ITEMS AFTER " + pause + " MS PAUSE *****");
            Thread.Sleep(pause);

            // Remove items
            for (int i = 1; i <= itemsToAdd; i++)
            {
                cacheClient.Remove("test" + i);
            }

            var key = Console.ReadKey();

            // Graceful shutdown option
            if (key.KeyChar == 'q')
            {
                cacheClient.Shutdown();
            }
        }
Beispiel #30
0
        public override void ExecuteCmdlet()
        {
            WriteWarning("Managed Cache will be retired on 11/30/2016. Please migrate to Azure Redis Cache. For more information, see http://go.microsoft.com/fwlink/?LinkID=717458");

            if (string.IsNullOrEmpty(ExpiryPolicy))
            {
                ExpiryPolicy = _DefaultExpiryPolicy;
            }

            if (ExpiryTime == null)
            {
                ExpiryTime = _DefaultExpiryTime;
            }

            string cacheServiceName = CacheClient.NormalizeCacheServiceName(Name);

            CacheClient.ProgressRecorder = (p) => { WriteVerbose(p); };
            WriteObject(new PSCacheServiceWithNamedCaches(CacheClient.AddNamedCache(cacheServiceName, NamedCache, ExpiryPolicy, (int)ExpiryTime,
                                                                                    WithoutEviction.IsPresent, WithNotifications.IsPresent, WithHighAvailability.IsPresent)));
        }
Beispiel #31
0
        public override void ExecuteCmdlet()
        {
            WriteWarning("Managed Cache will be retired on 11/30/2016. Please migrate to Azure Redis Cache. For more information, see http://go.microsoft.com/fwlink/?LinkID=717458");

            ConfirmAction(
                Force.IsPresent,
                string.Format(Properties.Resources.RemoveServiceWarning, Name),
                Properties.Resources.RemoveServiceMessage,
                Name,
                () =>
            {
                WriteVerbose(Properties.Resources.CacheServiceRemoveStarted);
                CacheClient.DeleteCacheService(Name);
                WriteVerbose(string.Format(Properties.Resources.CacheServiceRemoved, Name));
                if (PassThru)
                {
                    WriteObject(true);
                }
            });
        }
        public static void Run()
        {
            int totalCallbacks = 0;
            var cacheClient = new CacheClient();

            // 502 chars = ~1 kb
            string value = "asdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasas";

            int itemsToAdd = 10;
            var pause = 2000;

            Console.WriteLine("***** BEGIN REMOVED ITEM CALLBACK TEST *****");
            Console.WriteLine();

            cacheClient.HostDisconnected += (sender, e) => { Console.WriteLine("*** Host disconnected"); };
            cacheClient.HostReconnected += (sender, e) => { Console.WriteLine("*** Host reconnected"); };
            cacheClient.CacheItemExpired += (sender, e) => { Interlocked.Increment(ref totalCallbacks); Console.WriteLine(string.Format("Cache key expired: {0}, Total Removed: {1}", e.CacheKey, totalCallbacks)); };

            // Add items
            for (int i = 1; i <= itemsToAdd; i++)
            {
                cacheClient.AddOrUpdate("test" + i, value, notifyRemoved: true);
            }

            Console.WriteLine("***** " + itemsToAdd + " ITEMS ADDED *****");
            Console.WriteLine("***** BEGIN REMOVING " + itemsToAdd + " ITEMS AFTER " + pause + " MS PAUSE *****");
            Thread.Sleep(pause);

            // Remove items
            for (int i = 1; i <= itemsToAdd; i++)
            {
                cacheClient.Remove("test" + i);
            }

            var key = Console.ReadKey();
            // Graceful shutdown option
            if (key.KeyChar == 'q')
            {
                cacheClient.Shutdown();
            }
        }
        /// <summary>Requests an individual ModProfile by id.</summary>
        public virtual void RequestModProfile(int id,
                                              Action <ModProfile> onSuccess, Action <WebRequestError> onError)
        {
            Debug.Assert(onSuccess != null);

            ModProfile profile = null;

            if (profileCache.TryGetValue(id, out profile))
            {
                onSuccess(profile);
                return;
            }

            CacheClient.LoadModProfile(id, (cachedProfile) =>
            {
                if (cachedProfile != null)
                {
                    profileCache.Add(id, cachedProfile);
                    onSuccess(cachedProfile);
                }
                else
                {
                    APIClient.GetMod(id, (p) =>
                    {
                        if (this != null)
                        {
                            profileCache[p.id] = p;

                            if (this.storeIfSubscribed &&
                                LocalUser.SubscribedModIds.Contains(p.id))
                            {
                                CacheClient.SaveModProfile(p, null);
                            }
                        }

                        onSuccess(p);
                    },
                                     onError);
                }
            });
        }
        public override void ExecuteCmdlet()
        {
            Utility.ValidateResourceGroupAndResourceName(ResourceGroupName, Name);
            if (!string.IsNullOrEmpty(Name))
            {
                if (!string.IsNullOrEmpty(ResourceGroupName))
                {
                    // Get single cache directly by RP call
                    WriteObject(new RedisCacheAttributes(CacheClient.GetCache(ResourceGroupName, Name), ResourceGroupName));
                }
                else
                {
                    // Get single cache from list of caches
                    RedisResource response = CacheClient.GetCache(Name);
                    WriteObject(new RedisCacheAttributes(response, Utility.GetResourceGroupNameFromRedisCacheId(response.Id)));
                }
            }
            else
            {
                // List all cache in given resource group if avaliable otherwise all cache in given subscription
                IPage <RedisResource>       response = CacheClient.ListCaches(ResourceGroupName);
                List <RedisCacheAttributes> list     = new List <RedisCacheAttributes>();
                foreach (RedisResource resource in response)
                {
                    list.Add(new RedisCacheAttributes(resource, ResourceGroupName));
                }
                WriteObject(list, true);

                while (!string.IsNullOrEmpty(response.NextPageLink))
                {
                    // List using next link
                    response = CacheClient.ListCachesUsingNextLink(ResourceGroupName, response.NextPageLink);
                    list     = new List <RedisCacheAttributes>();
                    foreach (RedisResource resource in response)
                    {
                        list.Add(new RedisCacheAttributes(resource, ResourceGroupName));
                    }
                    WriteObject(list, true);
                }
            }
        }
        public void Execute(IJobExecutionContext context)
        {
            _logger.Info("启动任务");
            try
            {
                // 清空表~
                var truncateResult = TireStockoutStatusWhileManager.TruncateTableInfo();
                _logger.Info($"TireStockoutStatusWhiteListJob==>删除{truncateResult}条数据");

                var pids = TireStockoutStatusWhileManager.SelectTiresMatchAndSaleQuantityMoreThanEight();
                if (pids.Any())
                {
                    var b = TireStockoutStatusWhileManager.JoinWhiteList(pids, _logger);
                    if (b)
                    {
                        using (var client = new CacheClient())
                        {
                            var result = client.RefreshTireStockoutStatusWhiteListCache();
                            result.ThrowIfException(true);
                            if (!result.Result)
                            {
                                _logger.Error("更新成功,刷新缓存失败");
                            }
                        }
                    }
                    else
                    {
                        _logger.Error("更新失败");
                    }
                }
                else
                {
                    _logger.Info("未获取到月销量大于等于8条或者原配的轮胎");
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
            }
            _logger.Info("任务完成");
        }
        public static void Run()
        {
            var cacheClient = new CacheClient();

            var stopwatch = new Stopwatch();

            var overallStopwatch = new Stopwatch();
            overallStopwatch.Start();

            // 502 chars = ~1 kb
            const string value = "asdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasasdfasdfasas";

            CustomObject myObject = new CustomObject();

            Console.WriteLine("***** BEGIN ADD 10000 TESTS *****");
            Console.WriteLine();

            #region Regular Add 10000 strings
            stopwatch.Start();
            for (int i = 1; i <= 10000; i++)
            {
                cacheClient.AddOrUpdate("test" + i, value);
            }
            stopwatch.Stop();

            Console.WriteLine("Add time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            #endregion

            #region Bulk Add 10000 strings
            var list = new List<KeyValuePair<string, object>>(10000);
            for (int i = 1; i <= 10000; i++)
            {
                list.Add(new KeyValuePair<string, object>("bulktest" + i, value));
            }

            stopwatch.Restart();
            cacheClient.AddOrUpdate(list);
            stopwatch.Stop();

            Console.WriteLine("Add Many time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            #endregion

            #region Tagged Add 10000 strings
            stopwatch.Restart();
            for (int i = 1; i <= 10000; i++)
            {
                cacheClient.AddOrUpdate("tagtest" + i, value, tagName: "demotag");
            }
            stopwatch.Stop();

            Console.WriteLine("Add Tagged time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            #endregion

            Console.WriteLine();
            Console.WriteLine("***** BEGIN SINGLE KEY GET TEST *****");
            Console.WriteLine();

            #region Regular Get 1 string proof
            string resultString = null;
            stopwatch.Restart();
            var result = cacheClient.TryGet("test5", out resultString) && string.Equals(resultString, value);
            stopwatch.Stop();

            Console.WriteLine("Get cache key \"test5\": time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            Console.WriteLine("Get cache key \"test5\": successful = " + result);
            Console.WriteLine("Get cache key \"test5\": result length: " + (resultString == null ? 0 : resultString.Length) + ", original length: " + value.Length);
            if (resultString != null)
            {
                var origHash = value.GetHashCode();
                var resultHash = resultString.GetHashCode();
                Console.WriteLine("Original String Hash Code: " + origHash + ", Result String Hash Code: " + resultHash);
            }
            #endregion

            Console.WriteLine();
            Console.WriteLine("***** BEGIN GET 10000 TESTS *****");
            Console.WriteLine();

            string otherValue = null;

            #region Regular Get 10000 strings
            stopwatch.Restart();
            for (int i = 1; i <= 10000; i++)
            {
                if (!cacheClient.TryGet("test" + i, out otherValue))
                {
                    Console.WriteLine("Get failed for cache key: " + "test" + i);
                }
            }
            stopwatch.Stop();

            Console.WriteLine("Get time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            #endregion

            #region Bulk Get 10000 strings
            var list2 = new List<string>(10000);
            for (int i = 1; i <= 10000; i++)
            {
                list2.Add("bulktest" + i);
            }

            stopwatch.Restart();
            var getManyResults = cacheClient.Get<string>(list2);
            stopwatch.Stop();

            Console.WriteLine("Get Many time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            Console.WriteLine("Get Many object count: " + getManyResults.Count);
            #endregion

            #region Tagged Get 10000 strings
            stopwatch.Restart();
            var getTaggedResults = cacheClient.GetTagged<string>("demotag");
            stopwatch.Stop();

            Console.WriteLine("Get Tagged time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            Console.WriteLine("Get Tagged object count: " + getManyResults.Count);
            #endregion

            Console.WriteLine();
            Console.WriteLine("***** BEGIN REMOVE 10000 TESTS *****");
            Console.WriteLine();

            #region Regular Remove 10000 strings
            stopwatch.Restart();
            for (int i = 1; i <= 10000; i++)
            {
                cacheClient.Remove("test" + i);
            }
            stopwatch.Stop();

            Console.WriteLine("Remove time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            #endregion

            #region Bulk Remove 10000 strings
            stopwatch.Restart();
            cacheClient.Remove(list2);
            stopwatch.Stop();

            Console.WriteLine("Remove Many time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            #endregion

            #region Tagged Remove 10000 strings
            stopwatch.Restart();
            cacheClient.RemoveTagged("demotag");
            stopwatch.Stop();

            Console.WriteLine("Remove Tagged time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            #endregion

            Console.WriteLine();
            Console.WriteLine("***** BEGIN ABSOLUTE EXPIRATION TEST *****");
            Console.WriteLine();

            #region Regular Add 10000 strings with absolute expiration
            var absoluteExpiration = DateTime.Now.AddMinutes(1);
            stopwatch.Restart();
            for (int i = 1; i <= 10000; i++)
            {
                cacheClient.AddOrUpdate("testabsolute" + i, value, absoluteExpiration: absoluteExpiration);
            }
            stopwatch.Stop();

            Console.WriteLine("Add absolute expiration time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            #endregion

            Console.WriteLine();
            Console.WriteLine("***** BEGIN 10000 COMPLEX OBJECT ADD TEST *****");
            Console.WriteLine();

            #region Regular Add 10000 complex objects with sliding expiration
            var slidingExpiration = new TimeSpan(0, 2, 0);
            stopwatch.Restart();
            for (int i = 1; i <= 10000; i++)
            {
                cacheClient.AddOrUpdate("testabsolutecomplex" + i, myObject, slidingExpiration: slidingExpiration);
            }
            stopwatch.Stop();

            Console.WriteLine("Add complex object time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            #endregion

            Console.WriteLine();
            Console.WriteLine("***** BEGIN 10000 COMPLEX OBJECT GET TEST *****");
            Console.WriteLine();

            #region Regular Get 10000 complex objects with sliding expiration
            stopwatch.Restart();
            for (int i = 1; i <= 10000; i++)
            {
                cacheClient.TryGet("testabsolutecomplex" + i, out myObject);
            }
            stopwatch.Stop();

            Console.WriteLine("Get complex object time taken: " + stopwatch.ElapsedMilliseconds + " ms, " + stopwatch.ElapsedTicks + " ticks");
            #endregion

            overallStopwatch.Stop();

            Console.WriteLine();
            Console.WriteLine("***** END TESTS *****");
            Console.WriteLine();

            Console.WriteLine("Total time taken: " + overallStopwatch.ElapsedMilliseconds + " ms, " + overallStopwatch.ElapsedTicks + " ticks");

            var key = Console.ReadKey();
            // Graceful shutdown option
            if (key.KeyChar == 'q')
            {
                cacheClient.Shutdown();
            }
        }
 public void Setup()
 {
     var connStr = "mongodb://*****:*****@ds063158.mongolab.com:63158/robertbird";
     var dbName = "robertbird";
     _client = new CacheClient(connStr, dbName);
 }