public async Task <GetTaskResponse> GetTaskDetails([FromQuery] long id) { try { #region validation if (id == 0) { throw ToDoExceptions.CreateExceptionRequiredFieldIsMissing(nameof(id)); } #endregion return(await _getTaskService.GetTaskAsync(id)); } catch (BaseException ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; // debug RedisProvider _redis = new RedisProvider(); _redis.Set <BaseException>("last-exception", ex); /// return(null); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(null); } }
public async Task DeleteTask(long id) { RedisProvider _redis = new RedisProvider(); var _key = $"{Constants.TASK_PREFIX}{Convert.ToString(id)}"; _redis.Delete(_key); }
static void Main(string[] args) { RedisProvider d = new RedisProvider(); var redis = d.GetDatabase(); User us = new User() { Id = 10000, Name = "loong", Password = "******" }; redis.JsonHashSet("User", "10000", us); us = new User() { Id = 10001, Name = "loong2", Password = "******" }; redis.JsonHashSet("User", "10001", us); us = redis.JsonHashGet <User>("User", "10000"); /////////////////////////////////////////////////////////////////////////////////// string key = "Token:10000"; redis.JsonSet(key, "0000000000000000", null); key = "Token:10001"; redis.JsonSet(key, "0000000000000000", null); }
/// <summary> /// 获取全部列表(Redis缓存) /// </summary> /// <returns></returns> public static List <Product_Class> GetListCache() { try { string key = "ProClass"; if (RedisProvider.KeyExistSync(key)) { string str = RedisProvider.StringGetSync(key); return(Tools.Tool.JsonHelper.Deserialize <Product_Class>(str)); } else { var list = GetList(); if (list != null && list.Count > 0) { //缓存过期时间-1天更新一次 TimeSpan ts = new TimeSpan(DateTime.Now.AddDays(1).Ticks - DateTime.Now.Ticks); RedisProvider.StringSetSync(key, Tools.Tool.JsonHelper.Serialize(list), ts); } return(list); } } catch (Exception ex) { Tools.Tool.LogHelper.WriteLog(typeof(BllProduct_Class), ex, Tools.Utility.User.GetMyMemberId(), Tools.Utility.User.GetMyMemberName()); return(null); } }
public async Task Should_Execute_In_Lock_By_Multiple_Threads() { //Arrange var redisProvider = new RedisProvider(_redisOptions); var tasks = new List <Task <(int RetryCount, DateTime BeginTime, DateTime EndTime, TimeSpan WaitTimeSpan)> >(); var results = new List <(int RetryCount, DateTime BeginTime, DateTime EndTime, TimeSpan WaitTimeSpan)>(); var dic = new Dictionary <int, int>(); var stopWatch = new Stopwatch(); var lockKey = Guid.NewGuid().ToString(); var WaitAndRetryFunc = default(Func <int, DateTime?, Task <(int RetryCount, DateTime BeginTime, DateTime EndTime, TimeSpan WaitTimeSpan)> >); WaitAndRetryFunc = async(retryCount, beginTime) => { if (!beginTime.HasValue) { beginTime = DateTime.Now; } try { await _lockService.ExecuteInLockAsync(lockKey, async() => { //await Task.Yield(); await Task.Delay(10); dic.Add(dic.Count + 1, Thread.CurrentThread.GetHashCode()); }); var now = DateTime.Now; var waitTimeSpan = now - beginTime.Value; return(retryCount, beginTime.Value, DateTime.Now, waitTimeSpan); } catch (DistributedLockTimeoutException) { retryCount++; return(await WaitAndRetryFunc(retryCount, beginTime)); } }; //Act stopWatch.Start(); for (int i = 0; i < 1000; i++) { //results.Add(await WaitAndRetryFunc(0, null)); tasks.Add(WaitAndRetryFunc(0, null)); } await Task.WhenAll(tasks); stopWatch.Stop(); //Assert results = tasks.Select(t => t.Result).ToList(); var retryMostTasks = results.Where(t => t.RetryCount == results.Max(l => l.RetryCount)).ToList(); var waitLongestTaks = results.Where(t => t.WaitTimeSpan == results.Max(l => l.WaitTimeSpan)).ToList(); //System.IO.File.WriteAllText(@"C:\Users\Caskia\Desktop\1.txt", $"retryCount:{retryMostTasks.FirstOrDefault().RetryCount}, waittime:{waitLongestTaks.FirstOrDefault().WaitTimeSpan.TotalMilliseconds}"); dic.Count.ShouldBe(1000); }
public static IServiceCollection AddTStackRedisCache(this IServiceCollection services, Func <RedisContextConfig> action) { var config = action(); var context = new RedisProvider(config, null); services.Add(ServiceDescriptor.Singleton <IRedisProvider>(context)); return(services); }
public static void AddRedis(this IServiceCollection services, Action <string, string> handle = null) { if (!ConnectionHelper.Redis.Any()) { return; } var cache = RedisProvider.Build(ConnectionHelper.Redis, handle); services.AddSingleton <IDistributedCache>(cache); }
/// <summary> /// 创建新 <see cref="CachedDataProvider" /> /// </summary> /// <param name="dbContext"> /// <see cref="KeylolDbContext" /> /// </param> /// <param name="redis"> /// <see cref="RedisProvider" /> /// </param> public CachedDataProvider(KeylolDbContext dbContext, RedisProvider redis) { Likes = new LikeOperations(dbContext, redis); Subscriptions = new SubscriptionOperations(dbContext, redis); Points = new PointOperations(dbContext, redis); Users = new UserOperations(dbContext, redis, Subscriptions); ArticleComments = new ArticleCommentOperations(dbContext, redis); ActivityComments = new ActivityCommentOperations(dbContext, redis); Messages = new MessageOperations(dbContext, redis); }
/// <summary> /// 实例化类 /// 默认过期120分钟 /// </summary> /// <param name="context"></param> /// <param name="IsReadOnly"></param> /// <param name="Timeout">单位(分)</param> public RedisSession(HttpContext context, bool IsReadOnly, int Timeout = 120) { this.context = context; this.IsReadOnly = IsReadOnly; this.Timeout = Timeout; TimeSpan ts = new TimeSpan((DateTime.Now.AddMinutes(Timeout) - DateTime.Now).Ticks); //更新缓存过期时间 RedisProvider.CacheKeyExpire(SessionID, ts); }
public PersistenceProviderContainer(ConnectionSettingsProvider settingsProvider) : base(settingsProvider) { Provider = new RedisProvider(_connector, _providerNamespace); var db = _connector.GetDatabase(); if (!db.KeyExists(GetKeyForEmployeesSet())) { GenereateDate(db); } }
// // 摘要: // 按名称获取或设置会话值。 // // 参数: // name: // 会话值的键名。 // // 返回结果: // 具有指定名称的会话状态值;如果该项不存在,则为 null。 public object this[string name] { get { return(RedisProvider.SessionHashGetSync(SessionID, name)); } set { RedisProvider.SessionHashSetSync(SessionID, name, value.ToString()); } }
public override void FixtureSetup() { XmlConfigurator.Configure(); _props = new Dictionary<string, string> {{RedisProvider.NoClearPropertyKey, "true"}, {AbstractCache.ExpirationPropertyKey, "20"}, {AbstractCache.LockAcquisitionTimeoutPropertyKey, "1"}, {AbstractCache.LockTimeoutPropertyKey, _lockTimeout.ToString()} }; _provider = new RedisProvider(); _provider.Start(_props); }
public UserService(RedisProvider redisProvider, IConfiguration config) { _redisProvider = redisProvider; if (config["BCryptWorkFactor"] != null) { _bcryptWorkFactory = int.Parse(config["BCryptWorkFactor"]); // use a differnet work factor } else { _bcryptWorkFactory = 11; // use the default } }
public async Task <GetTasksResponse> GetTasksAsync() { RedisProvider _redis = new RedisProvider(); //todo add async var _data = _redis.ScanAndGet <ToDoTask>($"{Constants.TASK_PREFIX}*"); return(new GetTasksResponse { Payload = _data, TotalCount = _data.Count }); }
public async Task <ToDoTask> ChangeTaskStatusAsync(long id) { RedisProvider _redis = new RedisProvider(); //todo rename with ctrl + R + R var _key = $"{Constants.TASK_PREFIX}{Convert.ToString(id)}"; var _data = _redis.Get <ToDoTask>(_key); _data.IsDone = !(_data.IsDone); _redis.Set(_key, _data); return(_data); }
public async Task <GetTaskResponse> GetTaskAsync(long id) { RedisProvider _redis = new RedisProvider(); //todo convert to string to tostring var _key = $"{Constants.TASK_PREFIX}{Convert.ToString(id)}"; var _data = _redis.Get <ToDoTask>(_key); return(new GetTaskResponse { Payload = _data, }); }
public async Task <bool> InstantiateCacheContainer(RedisProvider redis, CancellationToken cancellationToken) { Console.WriteLine("---- Starting Deploy Cache Container ----"); await DownloadImage("redis", cancellationToken); var createParameters = new CreateContainerParameters() { Image = "redis", Name = CacheContainerName, Cmd = new List <string>() { $"redis-server", "--requirepass", $"{redis.Password}" } }; return(await DeployAndStartAsync(CacheContainerName, createParameters, cancellationToken)); }
public async Task <ToDoTask> AddTask([FromBody] AddTaskParams parameters) { try { #region validation if (parameters == null) { throw ToDoExceptions.CreateExceptionBadParam(nameof(parameters), "null", "Parameters is null"); } if (parameters.Id == 0) { throw ToDoExceptions.CreateExceptionRequiredFieldIsMissing(nameof(parameters.Id)); } if (parameters.Name == null) { throw ToDoExceptions.CreateExceptionRequiredFieldIsMissing(nameof(parameters.Name)); } #endregion return(await _postTaskService.AddTaskAsync( parameters.Id, parameters.Name, parameters.Description)); } catch (BaseException ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; // debug RedisProvider _redis = new RedisProvider(); _redis.Set <BaseException>("last-exception", ex); /// return(null); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(null); } }
public TwoLevelCacheProvider(IOptions <MemoryCacheOptions> options, RedisProvider redisProvider, IMemoryCache memoryCache, IOptions <CacheManagerOptions> cacheManagerOptions) { var cacheOptions = cacheManagerOptions.Value.CacheOptions; foreach (var(cacheName, _) in cacheOptions) { var redisCache = redisProvider.GetCache(cacheName); options.Value.CacheOptions.TryGetValue(cacheName, out var memoryCacheOptions); var cacheWrapper = new TwoLevelCache( redisCache, memoryCache, cacheName, memoryCacheOptions?.EntityCacheOptions ?? options.Value.DefaultOptions, memoryCacheOptions?.SetsCacheOptions ?? options.Value.DefaultOptions); _caches.Add(cacheName, cacheWrapper); } }
public async Task <IActionResult> Index() { ViewBag.Company = "Welfull"; ViewBag.Name = "Harry"; //创建数组 string[] names = new string[] { "ZeosonY", "XuZ", "Owen", "Actor", "Director" }; ViewBag.Names = names; //创建字典 Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("ZeosonY", "想做鱼"); dic.Add("XuZ", "Lave"); dic.Add("Owen", "Owen"); dic.Add("Actor", "演员"); dic.Add("Director", "导演"); //插入到redis-string RedisProvider.StringSetSync(dic); //插入到redis-list foreach (var item in dic) { //左侧插入 await RedisProvider.ListLPush("MyList", item.Value); //从右侧删除并获取 await RedisProvider.ListRightPop("MyList"); } //string对集合 NameValueCollection list = new NameValueCollection(); list.Add("XuZ", "username1"); list.Add("XuZ", "username2"); list.Add("LiuD", "username3"); //设置cookie Tools.Utility.CookieHelper.SetObj("XXX", 120, list); Tools.Utility.CookieHelper.SetObj("YZX", 120, "XZY"); ViewBag.Dic = dic; return(View()); }
public async Task <bool> InstantiateCacheContainer(RedisProvider redis, CancellationToken cancellationToken) { logger.Information("---- Starting Deploy Cache Container ----"); await DownloadImage("redis", cancellationToken); var ports = new Dictionary <string, EmptyStruct>(); ports.Add("6379/tcp", new EmptyStruct()); var createParameters = new CreateContainerParameters() { Image = "redis", Name = CacheContainerName, Cmd = new List <string>() { $"redis-server", "--requirepass", $"{redis.Password}" }, Hostname = CacheContainerName, ExposedPorts = ports, HostConfig = new HostConfig() { NetworkMode = NetworkName, RestartPolicy = new RestartPolicy() { Name = RestartPolicyKind.Always }, PortBindings = new Dictionary <string, IList <PortBinding> > { { "6379/tcp", new List <PortBinding> { new PortBinding { HostPort = "6379" } } } } } }; return(await DeployAndStartAsync(CacheContainerName, createParameters, cancellationToken)); }
public async Task <ToDoTask> AddTaskAsync( long id, string name, string description) { RedisProvider _redis = new RedisProvider(); var _task = new ToDoTask { Id = id, Name = name, Description = description }; var key = $"{Constants.TASK_PREFIX}{ Convert.ToString(id) }"; _redis.Set(key, _task); return(_task); }
public async Task <IActionResult> Detail() { //读取redis设置的其中一个string值 string value1 = await RedisProvider.StringGet("ZeosonY"); string value2 = await RedisProvider.StringGet("XuZ"); string value3 = await RedisProvider.StringGet("Owen"); string value4 = await RedisProvider.StringGet("Actor"); string value5 = await RedisProvider.StringGet("Director"); //读取redis设置的list List <string> list = await RedisProvider.ListRange("MyList", 0, -1); //读取设置的cookie string cookie1 = Tools.Utility.CookieHelper.GetValue("YZX"); string cookie2 = Tools.Utility.CookieHelper.GetValue("XXX"); //测试分页 int page = RequestInt("page"); page = page == 0 ? 1 : page; long records = 0; int pageSize = 10; var userList = Bll.BllUser.Instance.GetPageList(page, pageSize, out records); string pageHtml = GetPageHtml(page, pageSize, records, 5, "/Home/Detail?page={0}"); ViewBag.cookie1 = cookie1; ViewBag.cookie2 = cookie2; ViewBag.name1 = value1; ViewBag.name2 = value2; ViewBag.name3 = value3; ViewBag.name4 = value4; ViewBag.name5 = value5; ViewBag.list = list; ViewBag.userList = userList; ViewBag.pageHtml = pageHtml; return(View(UserService.CurrentUser)); }
//Redis public static void RedisCaching(int[] numForFibbonachi) { var redisCache = new RedisProvider(); for (int i = 0; i < numForFibbonachi.Length; i++) { Console.WriteLine("For item {0} Fibonacci sequence is:", numForFibbonachi[i]); var sequenceFromCache = redisCache.GetFromRedis <int>(numForFibbonachi[i].ToString()); if (sequenceFromCache != null) { Console.WriteLine("value from Cache"); WriteResult(sequenceFromCache); } else { var sequence = GetFibonacciSequence(numForFibbonachi[i]); redisCache.AddToRedis(numForFibbonachi[i].ToString(), sequence); WriteResult(sequence); } } }
public async Task Should_Redis_Set_By_Multiple_Threads() { var redisProvider = new RedisProvider(_redisOptions); var database = redisProvider.GetDatabase(); var tasks = new List <Task>(); var dic = new Dictionary <int, int>(); for (int i = 0; i < 1000; i++) { //tasks.Add(Task.Factory.StartNew(t => RunLock(database, (int)t), i)); tasks.Add(RunLockAsync(database, i)); //tasks.Add(Task.Factory.StartNew(t => database.StringSet(t.ToString(), "test", TimeSpan.FromSeconds(30)), i)); //tasks.Add(database.StringSetAsync(i.ToString(), "test", TimeSpan.FromSeconds(30))); } await Task.WhenAll(tasks); await Task.Delay(5000); }
public async Task Should_Execute_In_Lock_By_Multiple_Threads() { //Arrange var redisProvider = new RedisProvider(_redisOptions); var tasks = new List <Task>(); var dic = new Dictionary <int, int>(); //Act for (int i = 0; i < 1000; i++) { //_lockService.ExecuteInLock("test", () => // { // dic.Add(dic.Count + 1, System.Threading.Thread.CurrentThread.GetHashCode()); // }); //await _lockService.ExecuteInLockAsync("test", () => //{ // dic.Add(dic.Count + 1, System.Threading.Thread.CurrentThread.GetHashCode()); //}); tasks.Add(_lockService.ExecuteInLockAsync("test", () => { dic.Add(dic.Count + 1, System.Threading.Thread.CurrentThread.GetHashCode()); })); //tasks.Add(Task.Factory.StartNew(() => // _lockService.ExecuteInLock("test", () => // { // dic.Add(dic.Count + 1, System.Threading.Thread.CurrentThread.GetHashCode()); // }) //)); } await Task.WhenAll(tasks); //Assert dic.Count.ShouldBe(400); }
public async Task DeleteTask(long id) { // Todo: fix api. case: if there is nothing to delete try { if (id == 0) { throw ToDoExceptions.CreateExceptionBadParam(nameof(id), id.ToString()); } await _deleteTaskService.DeleteTask(id); } catch (BaseException ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; // debug RedisProvider _redis = new RedisProvider(); _redis.Set <BaseException>("last-exception", ex); /// } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; } }
/// <summary> /// 获取指定据点的评分 /// </summary> /// <param name="pointId">据点 ID</param> /// <exception cref="ArgumentNullException"><paramref name="pointId"/> 为 null</exception> /// <returns>据点评分</returns> public async Task <PointRatingsDto> GetRatingsAsync([NotNull] string pointId) { if (pointId == null) { throw new ArgumentNullException(nameof(pointId)); } var cacheKey = RatingCacheKey(pointId); var redisDb = _redis.GetDatabase(); var cacheResult = await redisDb.StringGetAsync(cacheKey); if (cacheResult.HasValue) { return(RedisProvider.Deserialize <PointRatingsDto>(cacheResult)); } var ratings = new PointRatingsDto(); var userRatings = new Dictionary <string, UserRating>(); foreach (var ratingEntry in await _dbContext.Articles .Where(a => a.TargetPointId == pointId && a.Rating != null && a.Archived == ArchivedState.None && a.Rejected == false) .Select(a => new { a.AuthorId, a.Rating }) .Union(_dbContext.Activities .Where(a => a.TargetPointId == pointId && a.Rating != null) .Select(a => new { a.AuthorId, a.Rating })) .ToListAsync()) { switch (ratingEntry.Rating.Value) { case 1: ratings.OneStarCount++; break; case 2: ratings.TwoStarCount++; break; case 3: ratings.ThreeStarCount++; break; case 4: ratings.FourStarCount++; break; case 5: ratings.FiveStarCount++; break; default: continue; } UserRating userRating; if (!userRatings.TryGetValue(ratingEntry.AuthorId, out userRating)) { userRatings[ratingEntry.AuthorId] = userRating = new UserRating(); } userRating.Count++; userRating.Total += ratingEntry.Rating.Value; } ratings.AverageRating = userRatings.Count < 3 ? (double?)null : Math.Round(userRatings.Values.Sum(r => r.Total * 2 / (double)r.Count) / userRatings.Count, 1); await redisDb.StringSetAsync(cacheKey, RedisProvider.Serialize(ratings), RatingUpdatePeriod); return(ratings); }
/// <summary> /// 创建 <see cref="PointOperations"/> /// </summary> /// <param name="dbContext"><see cref="KeylolDbContext"/></param> /// <param name="redis"><see cref="RedisProvider"/></param> public PointOperations(KeylolDbContext dbContext, RedisProvider redis) { _dbContext = dbContext; _redis = redis; }
public Server(IMQTTSettings settings, IChannelHandlerFactory chf, ServerSpotifyAuth spot, RedisProvider redis) : base(settings.Broker, settings.Port, settings.Username, settings.Password) { _spot = spot; _redisconnection = redis.redis; _redis = _redisconnection.GetDatabase(); LogTo.Trace("Initializing routes"); ////// // User messages ////// /// // Handle user-channel interaction On["/user/{username}/{channel}/songs/{songid}"] = msg => { switch ((string)msg.Message) { case "vote": AddVote(msg.channel, msg.songid, msg.username); break; case "unvote": RemoveVote(msg.channel, msg.songid, msg.username); break; case "report": ReportSong(msg.channel, msg.songid, msg.username); break; case "remove": RemoveSong(msg.channel, msg.songid, msg.username); break; case "block": BlockSong(msg.channel, msg.songid, msg.username); break; default: LogTo.Warn("[{0}] Invalid command: {1}: {2}, by {3}", (string)msg.channel, (string)msg.Topic, (string)msg.Message, (string)msg.username); break; } }; // Handle channel registration On["/user/{username}/register/{channel}"] = _ => { // TODO Separate channel name from ID Channel channel = JsonConvert.DeserializeObject <Channel>(_.Message); if (channel == null || string.IsNullOrWhiteSpace(channel.Name)) { LogTo.Warn("Rejected invalid channel JSON from {0} for channel {1}: {2}", (string)_.username, (string)_.channel, (string)_.Message); return; } LogTo.Info("[{0}] {1} sent channel data: {2}", (string)_.channel, (string)_.username, (string)_.Message); if (!_redis.KeyExists(GetChannelNameID(_.channel))) { // Channel doesn't exist yet LogTo.Info("[{0}] Setting up new channel for {1}", (string)_.channel, (string)_.username); _redis.StringSet(GetChannelNameID(_.channel), channel.Name); _redis.StringSet(GetChannelDescriptionID(_.channel), channel.Description); _redis.SetAdd(GetChannelModeratorID(_.channel), _.username); } else { // Channel exists if (!_redis.SetContains(GetChannelModeratorID(_.channel), _.username)) { LogTo.Error("[{0}] Error: User {1} not a moderator of channel", (string)_.channel, (string)_.username); return; } LogTo.Info("[{0}] changing existing channel for {1}", (string)_.channel, (string)_.username); _redis.StringSet(GetChannelNameID(_.channel), channel.Name); _redis.StringSet(GetChannelDescriptionID(_.channel), channel.Description); } Publish(string.Format("/{0}/info", _.channel), _.Message, true); }; // Handle user chat messages On["/user/{username}/{channel}/chat"] = _ => { LogTo.Trace("{0}->{1}: {2}", (string)_.username, (string)_.channel, (string)_.Message); // TODO [LOW] Allow moderators to mute users if (channels.ContainsKey(_.channel)) { var topic = string.Format("/{0}/chat", _.channel); var message = new ChatMessage { message = _.Message, username = _.username, time = Time.Timestamp() }; var messageJson = JsonConvert.SerializeObject(message); Publish(topic, messageJson); HipchatSender.SendNotification(_.channel, string.Format("{0}: {1}", message.username, message.message), RoomColors.Gray); } else { LogTo.Debug("Chat was for invalid channel"); } }; ////// // Channel messages ////// // TODO: This should be separate from above // Handle channel info On["/{channel}/info"] = _ => { LogTo.Info("[{0}] Got info: {1}", (string)_.channel, (string)_.Message); Channel channel = JsonConvert.DeserializeObject <Channel>(_.Message); if (!channels.ContainsKey(_.channel)) { ChannelHandler channelHandler = chf.CreateChannelHandler(_.channel); channelHandler.Subscribe(); channels[_.channel] = channelHandler; StartChannelScheduler(channelHandler); } }; }
public BookService(RedisProvider redisProvider) { _redisProvider = redisProvider; }