public void WhenNewWithMux_Should_Create_ExistingRedisConnection() { var mockOfMux = new Mock <IConnectionMultiplexer>(); var cnx = RedisConnectionFactory.New(mockOfMux.Object); Assert.IsType <ExistingRedisConnnection>(cnx); }
public void Add(IConnectOptions connectOptions, RedisConnectionFactory factory) { lock (_synch) { Interlocked.Increment(ref _count); IConnectOptions oldConnectOptions = null; if (_keys.TryGetValue(connectOptions.TagName, out oldConnectOptions)) { RedisConnectionFactory oldFactory = null; //但是属性已发生变更 if (connectOptions.CompareTo(oldConnectOptions) == 0) { _keys.Remove(connectOptions.TagName); _queue.TryDequeue(out oldFactory); //重新入队 _keys.Add(connectOptions.TagName, connectOptions); _queue.Enqueue(factory); } } else { _keys.Add(connectOptions.TagName, connectOptions); _queue.Enqueue(factory); } Interlocked.Decrement(ref _count); } }
public async Task <IActionResult> Index() { RedisConnectionFactory.GetConnection().GetDatabase().StringSet("redis::isSubmit", "false"); var isEnabled = RedisConnectionFactory.GetConnection().GetDatabase().StringGetAsync("redis::isSubmit") .Result.ToString(); if (!string.IsNullOrEmpty(isEnabled) && isEnabled == "true") { ViewBag.IsEnabled = true; } else { ViewBag.IsEnabled = false; } _ = Task.Run(async() => { while (true) { try { await _aliexpressHub.UpdateTotalCounter(); Thread.Sleep(2000); } catch (Exception ex) { var t = ex; } } }); return(View()); }
/// <summary> /// 设置值 /// </summary> public void Put(TKey key, TValue value, TimeSpan keepTime) { // 如果以前序列化失败过,直接使用备用的缓存 if (SerializeFailedTypes.ContainsKey(typeof(TKey)) || SerializeFailedTypes.ContainsKey(typeof(TValue))) { FallbackCache.Put(key, value, keepTime); return; } // 尝试序列化key和value,失败时使用备用的缓存 string keyJson, valueJson; try { keyJson = JsonConvert.SerializeObject(key); } catch { SerializeFailedTypes[typeof(TKey)] = true; FallbackCache.Put(key, value, keepTime); return; } try { valueJson = JsonConvert.SerializeObject(value); } catch { SerializeFailedTypes[typeof(TValue)] = true; FallbackCache.Put(key, value, keepTime); return; } // 保存到Redis var db = RedisConnectionFactory.GetDatabase(); db.StringSet(UniquePrefix + keyJson, valueJson, keepTime); }
public bool TryGet(out RedisConnectionFactory factory) { RedisConnectionFactory temp = null; lock (_synch) { if (this.Get(out temp)) { factory = temp; return(true); } else { for (var i = 0; i < 5; i++) { if (this.Get(out temp)) { factory = temp; return(true); } Thread.Sleep(i); } factory = null; return(false); } } }
public static void UseRedisCaching(this IServiceCollection serviceCollection, IEnumerable <string> hosts, uint dataBase) { serviceCollection.AddSingleton(RedisConnectionFactory.BuildConnectionMultiplexer(hosts)); serviceCollection.AddTransient <ICacheStore>(sp => new RedisCacheStore(sp.GetService <IConnectionMultiplexer>(), (int)dataBase)); serviceCollection.AddTransient <ICacheService, CacheService>(); }
public ResponseRewindMiddleware(RequestDelegate next, IBasePage basePage, UserManager <ApplicationUser> UserManager, RedisConnectionFactory Factory) { this.next = next; _basePage = basePage; _userManager = UserManager; _fact = Factory; }
/// <summary> /// 获取值 /// </summary> public bool TryGetValue(TKey key, out TValue value) { // 先从备用的缓存获取 if (FallbackCache.TryGetValue(key, out value)) { return(true); } // 不存在时尝试序列化key,失败时返回false string keyJson; try { keyJson = JsonConvert.SerializeObject(key); } catch { SerializeFailedTypes[typeof(TKey)] = true; return(false); } // 从Redis获取 var db = RedisConnectionFactory.GetDatabase(); var redisValue = db.StringGet(UniquePrefix + keyJson); if (!redisValue.HasValue) { return(false); } // 反序列化值,失败时返回false try { value = JsonConvert.DeserializeObject <TValue>(redisValue.ToString()); } catch { SerializeFailedTypes[typeof(TValue)] = true; return(false); } return(true); }
public RedisStageDirectory(RedisConnectionFactory connectionFactory, ILogger <RedisStageDirectory> logger, IOptions <NanoServiceOptions> serviceOptions, ITransportSerializer serializer) { _connectionFactory = connectionFactory; _serviceOptions = serviceOptions.Value; _serializer = serializer; _logger = logger; var cacheOptions = Microsoft.Extensions.Options.Options.Create <MemoryCacheOptions>(new MemoryCacheOptions() { }); _memoryCache = new MemoryCache(cacheOptions); _updateTask = Task.Run(async() => { while (true) { try { await GetAllStages(true); await Task.Delay(TimeSpan.FromSeconds(1)); } catch { await Task.Delay(TimeSpan.FromSeconds(2)); } } }); }
/// <summary> /// 删除文件 /// </summary> public void Delete() { var db = RedisConnectionFactory.GetDatabase(); db.KeyDelete(FileKeyPrefix + FullPath); Body = null; }
/// <summary> /// 更新文件内容 /// </summary> internal void UpdateBody(RedisFileBody body) { var db = RedisConnectionFactory.GetDatabase(); db.StringSet(FileKeyPrefix + FullPath, JsonConvert.SerializeObject(body)); Body = body; }
public ChatMessagesController(UserManager <AppUser> userManager, IUsersRepository usersRepository) { _chatRepo = new ChatDataRepository(); _redis = RedisConnectionFactory.GetConnection(); _database = _redis.GetDatabase(); _usersRepository = usersRepository; _userManager = userManager; }
public ChatHub(IHubContext <ChatHub> hubContext, IUsersRepository usersRepository) { _chatRepo = new ChatDataRepository(); _redis = RedisConnectionFactory.GetConnection(); _database = _redis.GetDatabase(); _hubContext = hubContext; _usersRepository = usersRepository; }
//<remark> Tight Coupled kod. Dışarıya interfaceler ile açılacak şekilde hazırladım.Constructer ın parametreleri elimde olmadığı için Loose Couple değil.</remark> public ConfigurationReader(string applicationName, string connectionString, int refreshTimerIntervalInMs) : base(new RedisCacher(new StackExchangeRedisCacheClient(RedisConnectionFactory.GetConnection(), new NewtonsoftSerializer())), new ConfigurationRepository(new DataHelper()), connectionString) { _applicationName = applicationName; _refreshTimerIntervalInMs = refreshTimerIntervalInMs; }
public RedisContext() { RedisConnectionFactory redisConnectinFactory = null; if (RedisConnectionPool.Instance.TryGet(out redisConnectinFactory)) { _redisConnectinFactory = redisConnectinFactory; } }
protected async override Task ExecuteAsync(CancellationToken stoppingToken) { DateTime lastRecord = DateTime.MinValue; while (!stoppingToken.IsCancellationRequested) { //var workItem = await TaskQueue.DequeueAsync(stoppingToken); DaegunPacket modbusWorkItem = await TaskQueue.DequeueAsync(stoppingToken); try { modbusWorkItem.timestamp = DateTime.Now; string pcs_key = $"site_{modbusWorkItem.sSiteId}_PCS"; string bsc_key = $"site_{modbusWorkItem.sSiteId}_BSC"; string ess_key = $"site_{modbusWorkItem.sSiteId}_ESSMETER"; string pv_key = $"site_{modbusWorkItem.sSiteId}_PVMETER"; HashEntry lastUpdate = new HashEntry("timestamp", DateTime.Now.ToString()); var hashPcsMap = RedisConnectionFactory.CreateHashEntries(modbusWorkItem.Pcs); hashPcsMap.Add(lastUpdate); var hashbmsMap = RedisConnectionFactory.CreateHashEntries(modbusWorkItem.Bsc, lastUpdate); var hashmeter_ess_Map = RedisConnectionFactory.CreateHashEntries(modbusWorkItem.Ess, lastUpdate); var hashmeter_pv_Map = RedisConnectionFactory.CreateHashEntries(modbusWorkItem.Pv, lastUpdate); await _redisDb.HashSetAsync(pcs_key, hashPcsMap.ToArray(), CommandFlags.FireAndForget); await _redisDb.HashSetAsync(bsc_key, hashbmsMap.ToArray(), CommandFlags.FireAndForget); await _redisDb.HashSetAsync(ess_key, hashmeter_ess_Map.ToArray(), CommandFlags.FireAndForget); await _redisDb.HashSetAsync(pv_key, hashmeter_pv_Map.ToArray(), CommandFlags.FireAndForget); _db = _client.GetDatabase("PEIU"); cols = _db.GetCollection <DaegunPacket>("daegun_meter"); lastRecord = DateTime.Now.Add(_mqttConfig.RecordInterval); await cols.InsertOneAsync(modbusWorkItem); _logger.LogInformation("Recorded packet from daegun"); //Console.WriteLine($"SAVE DB"); // if(workItem != null) // await workItem(stoppingToken); //if (modbusWorkItem != null) // await modbusWorkItem.RunAsync(stoppingToken); } catch (Exception ex) { _logger.LogError(ex, $"Error occurred executing {nameof(modbusWorkItem)}."); } } _logger.LogInformation("Queued Hosted Service is stopping."); }
public static IDatabase GetDatabase() { if (db == null) { //Store to Redis var RedisConnection = RedisConnectionFactory.GetConnection(); db = RedisConnection.GetDatabase(); } return(db); }
public SignalRService(ILogger <SignalRService> logger, IMediator mediator, IFrontTrnRepository frontTrnRepository, RedisConnectionFactory Factory) { _fact = Factory; _logger = logger; _mediator = mediator; // _TransactionRepository = TransactionRepository; _frontTrnRepository = frontTrnRepository; //_TradeTransactionRepository = TradeTransactionRepository; }
private void AddRedis() { var redisConfiguration = Configuration.GetSection("Redis").Get <RedisConfiguration>(); container.Register <IRedisConfiguration>(() => redisConfiguration, Lifestyle.Singleton); container.Register <IRedisConnectionFactory, RedisConnectionFactory>(Lifestyle.Singleton); var redisConnectionFactory = new RedisConnectionFactory(redisConfiguration); redisConnectionFactory.Connection.GetDatabase().Ping(); }
public void Can_Execute_PONG_Command() { var factory = new RedisConnectionFactory(redis_connection); using var connection = factory.Open(); var command = RedisCommand.Create(RedisCommands.PING); var response = command.Execute(connection); var message = response[0].AsString(); Assert.AreEqual("PONG", message); }
public RedisPubSub(IServiceProvider services, RedisConnectionFactory connectionFactory, ITelemetry telemetry) { _services = services; _telemetry = telemetry; _connectionFactory = connectionFactory; _subscriberLazy = new Lazy <ISubscriber>(() => { _connectionFactory.GetConnection().PreserveAsyncOrder = false; return(_connectionFactory.GetSubscriber()); }); }
public void Can_Connect() { var factory = new RedisConnectionFactory(redis_connection); using var connection = factory.Open(); var command = RedisCommand.Create(RedisCommands.PING); var response = command.Execute(connection); var message = response[0].AsString(); Assert.IsTrue(connection.IsOpen); Assert.IsTrue(connection.IsActive); Assert.IsFalse(connection.IsPassThrough); }
private bool Get(out RedisConnectionFactory factory) { RedisConnectionFactory temp = null; if (_queue.TryDequeue(out temp)) { factory = temp; _queue.Enqueue(temp); return(temp.IsOpend); } factory = null; return(false); }
/// <summary> /// 删除文件夹 /// </summary> public void Delete() { var db = RedisConnectionFactory.GetDatabase(); foreach (var endpoint in RedisConnectionFactory.GetEndPoints()) { var server = RedisConnectionFactory.GetServer(endpoint); foreach (var key in server.Keys()) { if (key.ToString().StartsWith(RedisFileEntry.FileKeyPrefix + FullPath + "/")) { db.KeyDelete(key); } } } }
public void RedisCategory(RedisCategoryUrlModel model) { if (model.Urls.Any()) { RedisConnectionFactory.GetConnection().GetDatabase().StringSet("redis::isSubmit", "true"); var data = new RedisMessageModel { IsRun = true, Urls = new List <string>() }; model.Urls.ForEach(n => data.Urls.Add(n)); RedisConnectionFactory.GetConnection().GetSubscriber().Publish("redis::runNode", JsonConvert.SerializeObject(data)); } }
public Task UpdateTotalCounter() { if (Clients != null) { var connection = RedisConnectionFactory.GetConnection(); connection.GetSubscriber().Subscribe("redis::totalCounter", (c, v) => { Clients.All.SendAsync("ReceiveMessage", "*", v); }); connection.GetSubscriber().Subscribe("redis::singleCount-1", (c, v) => { Clients.All.SendAsync("SingleCounterMessage", "*", 1 + "|" + v); }); connection.GetSubscriber().Subscribe("redis::singleCount-2", (c, v) => { Clients.All.SendAsync("SingleCounterMessage", "*", 2 + "|" + v); }); connection.GetSubscriber().Subscribe("redis::singleCount-3", (c, v) => { Clients.All.SendAsync("SingleCounterMessage", "*", 3 + "|" + v); }); connection.GetSubscriber().Subscribe("redis::singleCount-4", (c, v) => { Clients.All.SendAsync("SingleCounterMessage", "*", 4 + "|" + v); }); connection.GetSubscriber().Subscribe("redis::singleCount-5", (c, v) => { Clients.All.SendAsync("SingleCounterMessage", "*", 5 + "|" + v); }); connection.GetSubscriber().Subscribe("redis::singleCount-6", (c, v) => { Clients.All.SendAsync("SingleCounterMessage", "*", 6 + "|" + v); }); connection.GetSubscriber().Subscribe("redis::singleCount-7", (c, v) => { Clients.All.SendAsync("SingleCounterMessage", "*", 7 + "|" + v); }); connection.GetSubscriber().Subscribe("redis::singleCount-8", (c, v) => { Clients.All.SendAsync("SingleCounterMessage", "*", 8 + "|" + v); }); } return(Task.CompletedTask); }
/// <summary> /// 删除所有缓存值 /// </summary> public void Clear() { var db = RedisConnectionFactory.GetDatabase(); foreach (var endpoint in RedisConnectionFactory.GetEndPoints()) { var server = RedisConnectionFactory.GetServer(endpoint); foreach (var key in server.Keys()) { if (key.ToString().StartsWith(UniquePrefix)) { db.KeyDelete(key); } } } FallbackCache.Clear(); }
public RedisActorDirectory(RedisConnectionFactory connectionFactory, IStageDirectory stageDirectory, IOptions <NanoServiceOptions> serviceOptions, ITransportSerializer serializer) { _connectionFactory = connectionFactory; _serviceOptions = serviceOptions.Value; _serializer = serializer; _stageDirectory = stageDirectory; var cacheOptions = Microsoft.Extensions.Options.Options.Create <MemoryCacheOptions>(new MemoryCacheOptions() { CompactOnMemoryPressure = false }); _memoryCache = new MemoryCache(cacheOptions); _scriptsLazy = new Lazy <RedisScripts>(() => { return(new RedisScripts(_database)); }); }
/// <summary> /// 获取缓存对象数量 /// </summary> public int Count() { int count = 0; foreach (var endpoint in RedisConnectionFactory.GetEndPoints()) { var server = RedisConnectionFactory.GetServer(endpoint); foreach (var key in server.Keys()) { if (key.ToString().StartsWith(UniquePrefix)) { count += 1; } } } count += FallbackCache.Count(); return(count); }
/// <summary> /// 删除值 /// </summary> public void Remove(TKey key) { // 先从备用的缓存删除 FallbackCache.Remove(key); // 尝试序列化key string keyJson; try { keyJson = JsonConvert.SerializeObject(key); } catch { SerializeFailedTypes[typeof(TKey)] = true; return; } // 从Redis删除 var db = RedisConnectionFactory.GetDatabase(); db.KeyDelete(UniquePrefix + keyJson); }
public void Index() { // Arrange var config = new ConfigurationOptions { EndPoints = { { "localhost", 6379 } } }; _multiplexer = ConnectionMultiplexer.Connect(config); var jsonSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects }; _connectionFactory = new RedisConnectionFactory(_multiplexer, config, jsonSettings); var controller = new HomeController(_connectionFactory); // Act var result = controller.Index() as ViewResult; // Assert Assert.IsNotNull(result); }