private Redis() { try { redis = ConnectionMultiplexer.Connect("localhost"); DB = redis.GetDatabase(); } catch (RedisConnectionException rce) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.Arguments = Environment.CurrentDirectory + @"\redis\redis.windows.conf"; startInfo.FileName = Environment.CurrentDirectory + @"\redis\redis-server.exe"; startInfo.WorkingDirectory = Environment.CurrentDirectory + @"\redis\"; Process p = Process.Start(startInfo); Thread.Sleep(200); for (int i = 0; i < 3; ++i) { try { redis = ConnectionMultiplexer.Connect("localhost"); DB = redis.GetDatabase(); break; } catch (RedisConnectionException rce2) { Thread.Sleep(1000); } } } }
public RedisServer() { ConfigurationOptions config=new ConfigurationOptions(); config.Password=ConfigurationSettings.AppSettings["RedisPass"]; config.EndPoints.Add(ConfigurationSettings.AppSettings["RedisServer"]); redis = ConnectionMultiplexer.Connect(config); companies_db = redis.GetDatabase(0); relations_db = redis.GetDatabase(1); }
public RedisAdaptor(List<EndPoint> endPoints) { var config = new ConfigurationOptions() { AllowAdmin = true, }; foreach (var endPoint in endPoints) { config.EndPoints.Add(endPoint); } muxerInstance = ConnectionMultiplexer.Connect(config); Handle = muxerInstance.GetDatabase(); var script = Load("update_multikeys_multifields.lua"); //todo a hack way .. to be changed later foreach (var endPoint in muxerInstance.GetEndPoints()) { var server = muxerInstance.GetServer(endPoint); updateScriptSha = server.ScriptLoad(script); } Handle.StringSet("test", "111"); }
internal WorkflowManagement(ConnectionMultiplexer mux, ITaskHandler taskHandler, WorkflowHandler workflowHandler, string identifier, IEnumerable<string> typesProcessed, ILua lua, EventHandler<Exception> exceptionHandler = null, Behaviours behaviours = Behaviours.All) { _taskHandler = taskHandler; _workflowHandler = workflowHandler; if (exceptionHandler != null) { ExceptionThrown += exceptionHandler; } _typesProcessed = typesProcessed; _db = mux.GetDatabase(); _sub = mux.GetSubscriber(); if (_typesProcessed == null || _typesProcessed.Count() == 0) { _sub.Subscribe("submittedTask", (c, v) => { ProcessNextTask(); }); } else { foreach(var t in _typesProcessed) { _sub.Subscribe("submittedTask:" + t, (c, v) => { ProcessNextTask(t); }); } } _sub.Subscribe("workflowFailed", (c, v) => { ProcessNextFailedWorkflow(); }); _sub.Subscribe("workflowComplete", (c, v) => { ProcessNextCompleteWorkflow(); }); _lua = lua; _lua.LoadScripts(_db, mux.GetServer("localhost:6379")); _identifier = identifier; if (behaviours.HasFlag(Behaviours.AutoRestart)) { var resubmittedTasks = ResubmitTasks(); foreach (var item in resubmittedTasks) { Console.WriteLine("Resubmitted {0}", item); } } }
public async Task OpenAsync(PartitionContext context) { if (!WebJobsHelper.RunAsWebJobs) Console.WriteLine(string.Format("EventProcessor initialization. Partition: '{0}', Offset: '{1}'", context.Lease.PartitionId, context.Lease.Offset)); partitionContext = context; var retries = 3; while (retries > 0) { try { retries--; hubClient = EventHubClient.CreateFromConnectionString( ConfigurationManager.ConnectionStrings["SigfoxDemoAlertSender"].ConnectionString, "alert"); cacheConnection = await ConnectionMultiplexer.ConnectAsync(ConfigurationManager.ConnectionStrings["SigfoxDemoCache"].ConnectionString); cacheDatabase = cacheConnection.GetDatabase(); sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SigfoxDemoDatabase"].ConnectionString); //sqlConnection.Open(); //sqlCommand = new SqlCommand("InsertAlert", sqlConnection) { CommandType = CommandType.StoredProcedure }; //sqlCommand.Parameters.Add(new SqlParameter("@Device", SqlDbType.VarChar)); retries = 0; } catch (Exception e) { Console.Error.WriteLine("Error opening destination Event Hub: " + e.Message); if (retries == 0) throw; } } checkpointStopWatch = new Stopwatch(); checkpointStopWatch.Start(); }
internal static void Run(StackExchange.Redis.ConnectionMultiplexer Redis) { var maxOps = (int)ScalingConstants.LastOperation; var rnd = new Random(); while (true) { var work = new Workpack(); work.Instance = new InstanceDescriptor() { Id = rnd.Next(MAX_SESSIONS).ToString() }; work.OpCode = (Operation)rnd.Next(maxOps); work.Input = new InputData(); while (work.Input.SecondOperand == 0) { work.Input.SecondOperand = rnd.NextDouble(); } RedisValue[] data = { Tools.Serialize(work) }; Redis.GetDatabase().ListRightPush(Tools.WORKQUEUE, data, CommandFlags.FireAndForget); Console.Write("."); } }
public async Task OpenAsync(PartitionContext context) { if (!WebJobsHelper.RunAsWebJobs) Console.WriteLine(string.Format("EventProcessor initialization. Partition: '{0}', Offset: '{1}'", context.Lease.PartitionId, context.Lease.Offset)); partitionContext = context; var retries = 3; while (retries > 0) { var s = string.Empty; try { retries--; s = "storage"; storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["SigfoxDemoStorage"].ConnectionString); var blobClient = storageAccount.CreateCloudBlobClient(); blobContainer = blobClient.GetContainerReference("device"); blobContainer.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Off }); blobContainer.CreateIfNotExists(); s = "cache"; cacheConnection = await ConnectionMultiplexer.ConnectAsync(ConfigurationManager.ConnectionStrings["SigfoxDemoCache"].ConnectionString); cacheDatabase = cacheConnection.GetDatabase(); s = "database"; sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SigfoxDemoDatabase"].ConnectionString); sqlConnection.Open(); sqlCommand = new SqlCommand("InsertMessage", sqlConnection) { CommandType = CommandType.StoredProcedure }; sqlCommand.Parameters.Add(new SqlParameter("@Device", SqlDbType.VarChar)); sqlCommand.Parameters.Add(new SqlParameter("@Data", SqlDbType.VarChar)); sqlCommand.Parameters.Add(new SqlParameter("@Mode", SqlDbType.TinyInt)); sqlCommand.Parameters.Add(new SqlParameter("@Periode", SqlDbType.TinyInt)); sqlCommand.Parameters.Add(new SqlParameter("@FrameType", SqlDbType.TinyInt)); sqlCommand.Parameters.Add(new SqlParameter("@Battery", SqlDbType.Float)); sqlCommand.Parameters.Add(new SqlParameter("@Temperature", SqlDbType.Float)); sqlCommand.Parameters.Add(new SqlParameter("@Humidity", SqlDbType.Float)); sqlCommand.Parameters.Add(new SqlParameter("@ILS", SqlDbType.Bit)); sqlCommand.Parameters.Add(new SqlParameter("@Light", SqlDbType.Float)); sqlCommand.Parameters.Add(new SqlParameter("@Version", SqlDbType.VarChar)); sqlCommand.Parameters.Add(new SqlParameter("@AlertCount", SqlDbType.Int)); sqlCommand.Parameters.Add(new SqlParameter("@TimeStamp", SqlDbType.DateTime)); sqlCommand.Parameters.Add(new SqlParameter("@Duplicate", SqlDbType.Bit)); sqlCommand.Parameters.Add(new SqlParameter("@Signal", SqlDbType.Float)); sqlCommand.Parameters.Add(new SqlParameter("@Station", SqlDbType.VarChar)); sqlCommand.Parameters.Add(new SqlParameter("@AvgSignal", SqlDbType.Float)); sqlCommand.Parameters.Add(new SqlParameter("@Latitude", SqlDbType.Float)); sqlCommand.Parameters.Add(new SqlParameter("@Longitude", SqlDbType.Float)); sqlCommand.Parameters.Add(new SqlParameter("@Rssi", SqlDbType.Float)); sqlCommand.Parameters.Add(new SqlParameter("@SeqNumber", SqlDbType.Int)); retries = 0; } catch (Exception e) { Console.Error.WriteLine("Error opening destination Event Hub: " + e.Message + "(" + s + ")"); if (retries == 0) throw; } } checkpointStopWatch = new Stopwatch(); checkpointStopWatch.Start(); }
/// <summary> /// Initializes a new instance of the <see cref="RedisCache"/> class. /// </summary> /// <param name="name">The name.</param> /// <param name="hostname">The hostname.</param> public RedisCache(string name, string hostname = "localhost") : base(name) { _redis = ConnectionMultiplexer.Connect(hostname); _redis.PreserveAsyncOrder = false; _redisDb = _redis.GetDatabase(); _level1Cache = new MemoryCache(name); }
public void Connect() { if (_connection == null) { _connection = ConnectionMultiplexer.Connect(_options.Configuration); _cache = _connection.GetDatabase(); } }
public async Task ConnectAsync() { if (_connection == null) { _connection = await ConnectionMultiplexer.ConnectAsync(_options.Configuration); _cache = _connection.GetDatabase(); } }
static void CleanRedis() { connection = Redis.ConnectionMultiplexer.Connect("localhost,allowAdmin=true"); server = connection.GetServer("localhost", 6379); server.FlushDatabase(); db = connection.GetDatabase(); }
static string getTokenDetails(string Key) { Redis.ConnectionMultiplexer connection = Redis.ConnectionMultiplexer.Connect("localhost,password=ZLDe3wse"); Redis.IDatabase db = connection.GetDatabase(); Redis.RedisValue Value = db.StringGet(Key); return(Value); }
public async Task Init(Logger logger, IProviderConfiguration config, string providerName, int numQueues) { _logger = logger; _redisListBaseName = $"orleans-{providerName}-queue"; ReadRedisConnectionParams(config); _connection = await ConnectionMultiplexer.ConnectAsync(_server); _database = _connection.GetDatabase(_databaseNum); logger.AutoInfo($"connection to Redis successful."); IsInitialised = true; }
private void InitRedisDb() { if (_redisDb == null) { StackExchange.Redis.ConnectionMultiplexer cm = ConnectionMultiplexer.Connect("127.0.0.1:6379"); _redisDb = cm.GetDatabase(1); } }
private RedisClient(IPEndPoint endPoint, ConnectionMultiplexer redis) : base(endPoint) { if (null == redis) { throw new ArgumentNullException("redis"); } this.redis = redis; this.db = redis.GetDatabase(); }
public async Task Init(IPEndPoint endpoint, System.Threading.CancellationToken cancel) { _connection = await StackExchange.Redis.ConnectionMultiplexer.ConnectAsync(endpoint.ToString()).ConfigureAwait(false); var db = _connection.GetDatabase(); var data = Enumerable.Range(0, 10).Select(i => (RedisValue)i.ToString("0000000000")).ToArray(); db.SetAdd("testkeySER", data); db.SetAdd("testkeySER2", data); db.StringSet("testkeySER3", "hi this is a test"); }
public async Task RunClient(Int32 id, System.Threading.CancellationToken cancel) { var db = _connection.GetDatabase(); var batch = db.CreateBatch(); var t1 = batch.SetMembersAsync("testkeySER"); var t2 = batch.SetMembersAsync("testkeySER2"); var t3 = batch.StringGetAsync("testkeySER3"); batch.Execute(); await Task.WhenAll(t1, t2, t3).ConfigureAwait(false); }
//------------------------------------------------------------------------- public DbClientRedis(string databaseName, string connectionString) { DatabaseNumber = int.Parse(databaseName); object asyncState = null; var c = ConfigurationOptions.Parse(connectionString); c.AllowAdmin = true; CM = ConnectionMultiplexer.Connect(c); DB = CM.GetDatabase(DatabaseNumber, asyncState); }
internal static void Execute(ConnectionMultiplexer redis) { Redis = redis; var db = Redis.GetDatabase(); Console.Clear(); SimpleTest(); Console.Write("<ENTER> to close "); Console.ReadLine(); }
public RedisConnectionManager(IConfig config) { ConfigurationOptions options = new ConfigurationOptions(); options.EndPoints.Add(config.GetString("redisCacheHostName"), config.GetInt("redisCachePortNumber")); options.Ssl = config.GetBool("redisCacheUseSSL"); options.Password = config.GetString("redisCachePassword"); options.AbortOnConnectFail = false; options.ConnectTimeout = 30000; connection = ConnectionMultiplexer.Connect(options); cache = connection.GetDatabase(); }
public async Task RunClient(Int32 id, System.Threading.CancellationToken cancel) { var key = id.ToString(); var db = _connection.GetDatabase(); var values = new[] { new HashEntry("Member1", "Value1"), new HashEntry("Member2", "Value2"), new HashEntry("Member3", "Value3"), new HashEntry("Member4", "Value4") }; var trans = db.CreateTransaction(); { trans.StringIncrementAsync(key + "1"); trans.StringSetAsync(key + "2", key); trans.HashSetAsync(key + "3", values); await trans.ExecuteAsync().ConfigureAwait(false); } }
private void Redis(string message) { if (_connection == null) { _connection = ConnectionMultiplexer.Connect(ConfigurationManager.ConnectionStrings["AzureRedis"].ToString()); if (_cache == null) { _cache = _connection.GetDatabase(); } } _cache.ListLeftPush("s", message); }
internal static void Run(StackExchange.Redis.ConnectionMultiplexer redis) { Console.WriteLine("Hit <ESC> to shutdown this worker."); Redis = redis; while ((!Console.KeyAvailable) || (Console.ReadKey().Key != ConsoleKey.Escape)) { var msg = Redis.GetDatabase().ListLeftPop(Tools.WORKQUEUE); if (!msg.IsNullOrEmpty) HandleClusterWork(msg); else Thread.Sleep(0); } }
public string Post([FromBody] string value) { var id = Guid.NewGuid().ToString(); try { StackExchange.Redis.ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost"); StackExchange.Redis.IDatabase redisDb = redis.GetDatabase(); this.SaveDataToRedis(redisDb, id, value); this.makeEvent(redis, id, value); } catch (Exception e) { Console.WriteLine(e.Message); } return(id); }
private bool CheckQueue(bool queueError) { if (_queue == null) { if (_connection == null) { _connection = ConnectionMultiplexer.Connect(ConfigurationManager.ConnectionStrings["AzureRedis"].ToString()); if (_cache == null) { _cache = _connection.GetDatabase(); } } queueError = true; } return queueError; }
public StackExchangeClientConnection(ProviderConfiguration configuration) { _configuration = configuration; ConfigurationOptions configOption; // If connection string is given then use it otherwise use individual options if (!string.IsNullOrEmpty(configuration.ConnectionString)) { configOption = ConfigurationOptions.Parse(configuration.ConnectionString); if (!string.IsNullOrEmpty(configOption.ServiceName)) { ModifyEndpointsForSentinelConfiguration(configOption); } } else { configOption = new ConfigurationOptions(); if (configuration.Port == 0) { configOption.EndPoints.Add(configuration.Host); } else { configOption.EndPoints.Add(configuration.Host + ":" + configuration.Port); } configOption.Password = configuration.AccessKey; configOption.Ssl = configuration.UseSsl; configOption.AbortOnConnectFail = false; if (configuration.ConnectionTimeoutInMilliSec != 0) { configOption.ConnectTimeout = configuration.ConnectionTimeoutInMilliSec; } if (configuration.OperationTimeoutInMilliSec != 0) { configOption.SyncTimeout = configuration.OperationTimeoutInMilliSec; } } _redisMultiplexer = LogUtility.logger == null ? ConnectionMultiplexer.Connect(configOption) : ConnectionMultiplexer.Connect(configOption, LogUtility.logger); _connection = _redisMultiplexer.GetDatabase(configuration.DatabaseId); }
internal static void WriteAndUnlock(ConnectionMultiplexer Redis, InstanceState state, string lockId) { var db = Redis.GetDatabase(); RedisKey keyLock = Tools.MakeLockKey(state.Id); RedisKey keyData = Tools.MakeDataKey(state.Id); var result = LockedAction(db, state.Id, lockId, (trans) => { trans.StringSetAsync(keyData, Tools.Serialize<InstanceState>(state)); trans.KeyDeleteAsync(keyLock); }); if (result) { db.HashSet(Tools.SESSIONLIST, state.Id, "1"); return; } }
public static void Setup() { try { var config = new ConfigurationOptions(); config.SyncTimeout = 5000; config.EndPoints.Add("rodricdegroote.redis.cache.windows.net"); config.Ssl = true; //dit is de key die gegenereerd wordt in portal.azure.com config.Password = "******"; connection = ConnectionMultiplexer.Connect(config); cache = connection.GetDatabase(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
internal static void Execute(ConnectionMultiplexer redis) { Redis = redis; var db = Redis.GetDatabase(); RedisKey keyInnen = "{{Tests:EstimatingPi}}:Innen"; RedisKey keyAussen = "{{Tests:EstimatingPi}}:Aussen"; var rnd = new Random(); double lastGuess = 3; double delta = 1; while(Math.Abs(delta) > 1e-10) { var x = rnd.NextDouble(); var y = rnd.NextDouble(); if (((x * x) + (y * y)) > 1) db.StringIncrement(keyAussen); else db.StringIncrement(keyInnen); if ((rnd.Next() % 2048) == 0) { var values = db.StringGet(new RedisKey[2] { keyAussen, keyInnen }); var total = (int)values[0] + (int)values[1]; var guess = 4.0 * (double)values[1] / total; delta = Math.Abs(guess - lastGuess); Console.Write("\r{0} tests, Pi = {1}, Delta = {2} \r", total, guess, delta); lastGuess = guess; } } Console.WriteLine(""); Console.WriteLine(""); Console.Write("<ENTER> to close ... "); Console.ReadLine(); }
internal static void Execute(ConnectionMultiplexer redis) { Redis = redis; db = Redis.GetDatabase(); Console.Clear(); InitValues(db); StartThread(); while (true) { RefreshScreen(); Thread.Sleep(500); while( Console.KeyAvailable) { switch (Console.ReadKey(true).Key) { case ConsoleKey.Escape: Interlocked.Exchange(ref thread_limit, 0); while (thread_limit < Interlocked.Add(ref thread_count, 0)) Thread.Sleep(0); return; case ConsoleKey.Add: StartThread(); break; case ConsoleKey.Subtract: StopThread(); break; default: // nix break; } } } }
public void Connect() { _connection = ConnectionMultiplexer.Connect(_redisuri); _cache = _connection.GetDatabase(); }
public async Task Init(IPEndPoint endpoint, System.Threading.CancellationToken cancel) { _connection = await StackExchange.Redis.ConnectionMultiplexer.ConnectAsync(endpoint.ToString()).ConfigureAwait(false); await _connection.GetDatabase().StringIncrementAsync("whatever").ConfigureAwait(false); }
public async Task RunClient(Int32 id, System.Threading.CancellationToken cancel) { var key = id.ToString(); var db = _connection.GetDatabase(); await db.StringIncrementAsync(key).ConfigureAwait(false); }
internal static void Execute(ConnectionMultiplexer redis) { Redis = redis; var db = Redis.GetDatabase(); Console.Clear(); if (db.HashLength(keyTest + ":CodeByIdent") < 1) { EmptySets(); FillAirports(); } while (true) { double lon, lat, range; Console.WriteLine(""); Console.Write("Longitude: "); if (!Double.TryParse(Console.ReadLine(), out lon)) break; ; Console.Write("Latitude: "); if (!Double.TryParse(Console.ReadLine(), out lat)) break; ; while( db.SetLength(keyTest + ":matchLast") > 0) db.SetPop(keyTest + ":matchLast"); range = 0.001; var funde = 0; var start = DateTime.Now; while (funde < 20) { Console.Write("\rSearching {0} km range, {1:N0} secs and {2} matches so far ... ", DegToKm(range), (DateTime.Now - start).TotalSeconds, funde); var matchLat = db.SortedSetRangeByScoreWithScores(keyTest + ":IdentByLat", lat - range, lat + range); var matchLon = db.SortedSetRangeByScoreWithScores(keyTest + ":IdentByLon", lon - range, lon + range); while (db.SetLength(keyTest + ":latMatch") > 0) db.SetPop(keyTest + ":latMatch"); foreach (var match in matchLat) db.SetAdd(keyTest + ":latMatch", match.Element); while (db.SetLength(keyTest + ":lonMatch") > 0) db.SetPop(keyTest + ":lonMatch"); foreach (var match in matchLon) db.SetAdd(keyTest + ":lonMatch", match.Element); db.SetCombineAndStore( SetOperation.Intersect, keyTest + ":matchThis", new RedisKey[] { keyTest + ":lonMatch", keyTest + ":latMatch" }); db.SetCombineAndStore( SetOperation.Difference, keyTest + ":matchNew", new RedisKey[] { keyTest + ":matchThis", keyTest + ":matchLast" }); db.SetCombineAndStore( SetOperation.Union, keyTest + ":matchLast", new RedisKey[] { keyTest + ":matchThis", keyTest + ":matchLast" }); foreach (var elm in db.SetMembers(keyTest + ":matchNew")) { var ident = elm; var code = db.HashGet(keyTest + ":CodeByIdent", elm); var name = db.HashGet(keyTest + ":NameByIdent", elm); var lat_found = db.SortedSetScore(keyTest + ":IdentByLat", elm).Value; var lon_found = db.SortedSetScore(keyTest + ":IdentByLon", elm).Value; var km = DegToKm( Math.Sqrt( (lat_found - lat) * (lat_found - lat) + (lon_found - lon) * (lon_found - lon))); ++funde; Console.WriteLine("\r- {0} {1} is {2} km away, at lat {3:N3} lon {4:N3}", code, name, km, lat_found, lon_found); } range = Math.Ceiling( 11000 * range) / 10000; } Console.WriteLine("\r{0} matche(s) found in {1:N0} seconds.", funde, (DateTime.Now-start).TotalSeconds); } Console.Write("<ENTER> to close "); Console.ReadLine(); }
private bool UnlockInstance(ConnectionMultiplexer cache) { var host = GetHost(cache); var result = false; try { logger.DebugWrite("UnlockInstance enter {0}: {1}, {2}", host, redisKey, LockId); result = (bool) cache.GetDatabase() .ScriptEvaluate(UnlockScript, new RedisKey[] {redisKey}, new RedisValue[] {LockId}, CommandFlags.DemandMaster); } catch (Exception ex) { logger.DebugWrite("Error unlocking lock instance {0}: {1}", host, ex.Message); } logger.DebugWrite("UnlockInstance exit {0}: {1}, {2}, {3}", host, redisKey, LockId, result); return result; }
private bool ExtendInstance(ConnectionMultiplexer cache) { var host = GetHost(cache); var result = false; try { logger.DebugWrite("ExtendInstance enter {0}: {1}, {2}, {3}", host, redisKey, LockId, expiryTime); var extendResult = (long) cache.GetDatabase() .ScriptEvaluate(ExtendIfMatchingValueScript, new RedisKey[] {redisKey}, new RedisValue[] {LockId, (int) expiryTime.TotalSeconds}, CommandFlags.DemandMaster); result = (extendResult == 1); } catch (Exception ex) { logger.DebugWrite("Error extending lock instance {0}: {1}", host, ex.Message); } logger.DebugWrite("ExtendInstance exit {0}: {1}, {2}, {3}", host, redisKey, LockId, result); return result; }
private bool LockInstance(ConnectionMultiplexer cache) { var host = GetHost(cache); var result = false; try { logger.DebugWrite("LockInstance enter {0}: {1}, {2}, {3}", host, redisKey, LockId, expiryTime); result = cache.GetDatabase().StringSet(redisKey, LockId, expiryTime, When.NotExists, CommandFlags.DemandMaster); } catch (Exception ex) { logger.DebugWrite("Error locking lock instance {0}: {1}", host, ex.Message); } logger.DebugWrite("LockInstance exit {0}: {1}, {2}, {3}", host, redisKey, LockId, result); return result; }
//[Test] //public void TestOpCountByVersionLocal_DownLevel() //{ // var config = new ConfigurationOptions // { // EndPoints = { { Config.LocalHost } }, // DefaultVersion = new Version(2, 6, 0), // CommandMap = CommandMap.Create( // new HashSet<string> { "info" }, false) // }; // using (var conn = ConnectionMultiplexer.Connect(config)) // { // TestLockOpCountByVersion(conn, 5, false); // TestLockOpCountByVersion(conn, 3, true); // //TestManualLockOpCountByVersion(conn, 5, false); // //TestManualLockOpCountByVersion(conn, 3, true); // } //} //[Test] //public void TestOpCountByVersionRemote() //{ // using (var conn = Config.GetRemoteConnection(open: false)) // { // TestLockOpCountByVersion(conn, 1, false); // TestLockOpCountByVersion(conn, 1, true); // //TestManualLockOpCountByVersion(conn, 1, false); // //TestManualLockOpCountByVersion(conn, 1, true); // } //} public void TestLockOpCountByVersion(ConnectionMultiplexer conn, int expected, bool existFirst) { const int DB = 0, LockDuration = 30; const string Key = "TestOpCountByVersion"; var db = conn.GetDatabase(DB); db.KeyDelete(Key); var newVal = "us:" + Config.CreateUniqueName(); string expectedVal = newVal; if (existFirst) { expectedVal = "other:" + Config.CreateUniqueName(); db.StringSet(Key, expectedVal, TimeSpan.FromSeconds(LockDuration)); } long countBefore = conn.GetCounters().Interactive.OperationCount; var taken = db.LockTake(Key, newVal, TimeSpan.FromSeconds(LockDuration)); long countAfter = conn.GetCounters().Interactive.OperationCount; string valAfter = db.StringGet(Key); Assert.AreEqual(!existFirst, taken, "lock taken"); Assert.AreEqual(expectedVal, valAfter, "taker"); Console.WriteLine("{0} ops before, {1} ops after", countBefore, countAfter); Assert.AreEqual(expected, (countAfter - countBefore), "expected ops (including ping)"); // note we get a ping from GetCounters }
internal static void Execute(ConnectionMultiplexer redis) { Redis = redis; var db = Redis.GetDatabase(); FillKnownBirthdays(); while (true) { Console.Clear(); Console.Write("Tell me your birthday! First the day (1..31) "); int tag = Math.Max(1, Math.Min(31, Int32.Parse(Console.ReadLine()))); Console.Write("Great! Now the month (1..12) "); int monat = Math.Max(1, Math.Min(12, Int32.Parse(Console.ReadLine()))); Console.Write("And the year please (four digits) "); int year = Math.Max(0, Math.Min(DateTime.Now.Year, Int32.Parse(Console.ReadLine()))); Console.WriteLine(""); var keyTag = keyTest + ":day:" + tag.ToString(); var keyMonat = keyTest + ":month:" + monat.ToString(); var keyJahr = keyTest + ":year:" + monat.ToString(); var matches = db.SetMembers(keyJahr); Console.WriteLine("In the same year " + matches.Length.ToString() + " people were also born."); /* don't print, too much stuff foreach (var match in matches) Console.WriteLine("- " + match); Console.WriteLine(""); */ matches = db.SetMembers(keyMonat); Console.WriteLine(matches.Length.ToString() + " people have their birthday in the same month."); /* don't print, too much stuff foreach (var match in matches) Console.WriteLine("- " + match); Console.WriteLine(""); */ matches = db.SetMembers(keyTag); Console.WriteLine("At the " + tag.ToString() + ". of a month " + matches.Length.ToString() + " people have their birthday."); /* don't print, too much stuff foreach (var match in matches) Console.WriteLine("- " + match); Console.WriteLine(""); */ Console.WriteLine(""); matches = db.SetCombine(SetOperation.Intersect, new RedisKey[] { keyTag, keyMonat, keyJahr }); Console.WriteLine("At the exact date when you were born " + matches.Length.ToString() + " other people were born:"); foreach (var match in matches) Console.WriteLine("- " + match); Console.WriteLine(""); matches = db.SetCombine(SetOperation.Intersect, new RedisKey[] { keyTag, keyMonat }); Console.WriteLine("You share your birthday with " + matches.Length.ToString() + " other people:"); foreach (var match in matches) Console.WriteLine("- " + match); Console.WriteLine(""); Console.WriteLine(""); Console.WriteLine("Let's just pick a random one from the same day:"); Console.WriteLine("- " + db.SetRandomMember(keyTag)); Console.WriteLine(""); Console.WriteLine("How awesome is that?"); Console.WriteLine("<ENTER> to try again"); Console.ReadLine(); } }
public void SendQueueAsyncAll(int num) { _queueError = false; HttpContext context = HttpContext.Current; ELSLogs esLog = new ELSLogs(); esLog = (ELSLogs)context.Items[Userlog]; if (_queue == null) { _queue = GetQueue(); if (_queue == null) { if (_connection == null) { _connection = ConnectionMultiplexer.Connect(ConfigurationManager.ConnectionStrings["AzureRedis"].ToString()); if (_cache == null) { _cache = _connection.GetDatabase(); } } _queueError = true; } } //get Userlog object and fill with response information // String message = ""; // message += esLog.ElsIpaddress + " - - " + esLog.ElsRequest + " " + esLog.ElsResponse + " none"; // string message = "115.88.32.21 luffy priate [" + DateTime.Now.ToString("dd/MMM/yyyy:HH:mm:ss.FFF zz") + "] \"PATCH /api/grade/3\" 206 172 \"http://elswebapi.azurewebsites.net/\" \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36\" 2shift 204 none"; //create multiple async task to send message to queue5 var username = new ArrayList { "BingLi", "HuoYong", "Sherry", "Shot", "Tzkwizard", "Luffy", "Ace", "Fuji","Keith" }; var auth = new ArrayList { "JianShi", "JiShi", "Godness", "Guarder", "Master", "Priate", "King", "Genius", "Detective" }; var load = new ArrayList { "miejianxuelong", "yujiafengjie", "shengguang", "miejihaijian", "yazhi", "baqi", "fire", "qifan","icestop" }; var api = new ArrayList { "GET /api/ElasticMapping/LogstashMap/", "POST /api/ElasticSearch/", "DELETE /api/cleangrade/", "PUT /api/grade/", "PATCH /api/grade/" }; for (var i = 0; i < num; i++) { Random x = new Random(); int p1 = x.Next(1, 256); int p2 = x.Next(1, 256); int p3 = x.Next(1, 256); int p4 = x.Next(1, 256); int r1 = x.Next(200, 208); int r2 = x.Next(300, 308); int b = x.Next(1, 1024); int m = x.Next(1, 22); int ap = x.Next(0, 5); int us = x.Next(0, 9); string message = p1 + "." + p2 + "." + p3 + "." + p4 + " " + username[us] + " " + auth[us] + " [" + DateTime.Now.ToString("dd/MMM/yyyy:HH:mm:ss.FFF zz") + "]" + " \"" + api[ap] + m + "\" " + +r1 + " " + b + " \"" + "http://LogSearch.azurewebsites.net/" + "\" " + "\"" + "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" + "\"" + " " + load[us] + " " + r2 + " none"; Thread.Sleep(10); var i1 = i; //Thread.Sleep(10); Task.Run(() => SendQueueAsync(i1, esLog, _queue, message)); } }