public void Set() { //应用场景: //Redis set对外提供的功能与list类似是一个列表的功能,特殊之处在于set是可以自动排重的,当你需要存储一个列表数据,又不希望出现重复数据时, //set是一个很好的选择,并且set提供了判断某个成员是否在一个set集合内的重要接口,这个也是list所不能提供的。 //比如在微博应用中,每个人的好友存在一个集合(set)中,这样求两个人的共同好友的操作,可能就只需要用求交集命令即可。 //Redis还为集合提供了求交集、并集、差集等操作,可以非常方便的实 var redis = new RedisHelper(); redis.AddItemToSet("A", "B"); redis.AddItemToSet("A", "C"); redis.AddItemToSet("A", "D"); redis.AddItemToSet("A", "E"); redis.AddItemToSet("A", "F"); redis.AddItemToSet("A", "F"); redis.AddItemToSet("B", "C"); redis.AddItemToSet("B", "F"); //求差集 Console.WriteLine("A,B集合差集"); redis.GetDifferencesFromSet("A", "B").ToList<string>().ForEach(e => Console.Write(e + ",")); //求集合交集 Console.WriteLine("\nA,B集合交集"); redis.GetIntersectFromSets(new string[] { "A", "B" }).ToList<string>().ForEach(e => Console.Write(e + ",")); //求集合并集 Console.WriteLine("\nA,B集合并集"); redis.GetUnionFromSets(new string[] { "A", "B" }).ToList<string>().ForEach(e => Console.Write(e + ",")); }
public override void OnException(ExceptionContext filterContext) { RedisHelper redis = new RedisHelper(1); redis.ListRightPush("errorMsg", "234234234"); filterContext.HttpContext.Response.Redirect("~/Error.html"); base.OnException(filterContext); }
public void List() { //应用场景: //Redis list的应用场景非常多,也是Redis最重要的数据结构之一。 //我们可以轻松地实现最新消息排行等功能。 //Lists的另一个应用就是消息队列,可以利用Lists的PUSH操作,将任务存在Lists中,然后工作线程再用POP操作将任务取出进行执行 var redis = new RedisHelper(); #region "List类型" redis.AddItemToList("userInfoId1", "123"); redis.AddItemToList("userInfoId1", "1234"); Console.WriteLine("List数据项条数:" + redis.GetListCount("userInfoId1")); Console.WriteLine("List数据项第一条数据:" + redis.GetItemFromList("userInfoId1", 0)); Console.WriteLine("List所有数据"); redis.GetAllItemsFromList("userInfoId1").ForEach(e => Console.WriteLine(e)); #endregion #region "List类型做为队列和栈使用" Console.WriteLine(redis.GetListCount("userInfoId1")); //队列先进先出 //Console.WriteLine(redis.DequeueItemFromList("userInfoId1")); //Console.WriteLine(redis.DequeueItemFromList("userInfoId1")); //栈后进先出 Console.WriteLine("出栈" + redis.PopItemFromList("userInfoId1")); Console.WriteLine("出栈" + redis.PopItemFromList("userInfoId1")); #endregion }
public void Hash() { //一个hashid可以存储多项信息,每一项信息也有自己的key var redis = new RedisHelper(); redis.SetEntryInHash("userInfoId", "name", "zhangsan"); redis.SetEntryInHash("userInfoId", "name1", "zhangsan1"); redis.SetEntryInHash("userInfoId", "name2", "zhangsan2"); redis.SetEntryInHash("userInfoId", "name3", "zhangsan3"); redis.GetHashKeys("userInfoId").ForEach(Console.WriteLine); redis.GetHashValues("userInfoId").ForEach(Console.WriteLine); }
private void InitRedis() { string filePath = Server.MapPath("~/Logs/"); ThreadPool.QueueUserWorkItem(o => { while (true) { RedisHelper redis = new RedisHelper(1); if (redis.ListLength("errorMsg") > 0) { string ex = redis.ListRightPop<string>("errorMsg"); if (ex != null) { //logger.Debug(ex); } else { Thread.Sleep(50); } } else { Thread.Sleep(50); } } }); }
public async Task <ProtoRoomInfo> GetRoomInfo(int roomId) { var bytes = await RedisHelper.HGetAsync <byte[]>(RedisConstants.HKeyRedis_Room, roomId.ToString()); return(ProtoRoomInfo.Parser.ParseFrom(bytes)); }
public MoneyRedisRepository(RedisHelper redis) : base(redis) { }
private T _ <T>(string key, Func <T> func = null, TimeSpan?expiredTime = null) { var result = RedisHelper.Get <T>(key); //引用类型 if (typeof(T).IsClass && result == null) { if (func == null) { return(default(T)); } var executeResult = func.Invoke(); if (executeResult == null) { return(default(T)); } if (expiredTime.HasValue) { RedisHelper.Set(key, executeResult, expiredTime.Value); } else { RedisHelper.Set(key, executeResult); } return(executeResult); } //值类型 else if (typeof(T).IsValueType) { if (typeof(T).Name.StartsWith("Nullable`1"))//可空类型 { if (result == null) { if (func == null) { return(default(T)); } var executeResult = func.Invoke(); if (executeResult == null) { return(default(T)); } if (expiredTime.HasValue) { RedisHelper.Set(key, executeResult, expiredTime.Value); } else { RedisHelper.Set(key, executeResult); } return(executeResult); } else { return(result); } } else//不可空 { if (result.ToString() == typeof(T).GetDefault().ToString()) { if (func == null) { return(default(T)); } var executeResult = func.Invoke(); if (executeResult == null) { return(default(T)); } if (expiredTime.HasValue) { RedisHelper.Set(key, executeResult, expiredTime.Value); } else { RedisHelper.Set(key, executeResult); } return(executeResult); } else { return(result); } } } return(result); }
public T Get <T>(string key) { var result = RedisHelper.Get <T>(key); return(result); }
static void Main(string[] args) { RedisHelper.StringSet(CacheFolderEnum.Folder1, "string", "hello world", 60); }
/// <summary> /// 防火墙拦截日志 /// </summary> /// <param name="s"></param> public static void InterceptLog(IpIntercepter s) { RedisHelper.IncrBy("interceptCount"); RedisHelper.LPush("intercept", s); }
/// <summary> /// 设置配置文件 /// </summary> /// <param name="Settings"></param> /// <returns></returns> public static bool Set(Dictionary <string, string> Settings) { RedisHelper.Set("Settings", Settings); return(true); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //全局过滤器 services.AddControllers(options => { options.Filters.Add(new AuthorizeFilter()); options.Filters.Add(new ModelActionFilter()); }) .ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; //抑制系统自带模型验证 }) .AddControllersAsServices(); services.AddScoped <IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped <IUserStore, UserStore>(); services.AddSingleton(new ContainerBuilder()); services.AddDbContext <AppDbContext>(options => { options.UseMySql(Configuration.GetConnectionString("MySqlConnection")); }).AddUnitOfWork <AppDbContext>(); //UnitOfWork services.AddCap(options => { options.UseEntityFramework <AppDbContext>(); options.UseRabbitMQ(o => { o.HostName = Configuration["RabbitMQ:HostName"]; o.VirtualHost = Configuration["RabbitMQ:VirtualHost"]; o.Port = int.Parse(Configuration["RabbitMQ:Port"]); o.UserName = Configuration["RabbitMQ:UserName"]; o.Password = Configuration["RabbitMQ:Password"]; }); options.FailedRetryCount = 5; options.FailedRetryInterval = 60; options.UseDashboard(); }); services.AddOpenApiDocument(settings => { settings.Title = "Auth Service"; settings.Description = "授权服务"; settings.Version = "v1"; settings.DocumentName = "auth"; settings.AddSecurity("身份认证Token", Enumerable.Empty <string>(), new NSwag.OpenApiSecurityScheme() { Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)", Name = "Authorization", In = NSwag.OpenApiSecurityApiKeyLocation.Header, Type = NSwag.OpenApiSecuritySchemeType.ApiKey }); }); services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(InMemoryConfig.GetApiResources()) .AddInMemoryIdentityResources(InMemoryConfig.GetIdentityResources()) .AddInMemoryClients(InMemoryConfig.GetClients()) .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>() .AddProfileService <ProfileService>() .AddExtensionGrantValidator <SmsVerficationCodeValidator>(); services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.ApiName = "authservice"; options.ApiSecret = "secret"; options.Authority = "http://localhost:5000"; options.RequireHttpsMetadata = false; }); var redis = new CSRedis.CSRedisClient(Configuration.GetSection("Redis:Host").Value); RedisHelper.Initialization(redis); services.AddSingleton <IDistributedCache>(new CSRedisCache(RedisHelper.Instance)); services.AddAutoMapper(); ConfigureContainer(new ContainerBuilder()); }
/// <summary> /// 搜索统计 /// </summary> public void StatisticsSearchKeywords() { RedisHelper.Set("SearchRank:Month", _searchDetailsService.GetRanks(DateTime.Today.AddMonths(-1))); RedisHelper.Set("SearchRank:Week", _searchDetailsService.GetRanks(DateTime.Today.AddDays(-7))); RedisHelper.Set("SearchRank:Today", _searchDetailsService.GetRanks(DateTime.Today)); }
public RedisCacheHandler(RedisHelper helper) { _helper = helper; }
public async Task StartAsync(CancellationToken cancellationToken) { RedisHelper.Initialization(new CSRedis.CSRedisClient(RedisOptions.ConnectionStrings.First().ToString())); await Task.CompletedTask; }
//请求开始时由ASP.NET调用此方法 public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { context.Response.ContentType = "text/plain"; string code = AppRequest.GetQueryString("code"); if (code.Length < 6) { context.Response.Write("fail"); } else { StringBuilder sErrInfo = new StringBuilder(256); StringBuilder sResult = new StringBuilder(1024 * 1024); byte[] market = null; List <byte> market_list = new List <byte>(); string[] code_list = code.Split(','); short count = (short)code_list.Length; if (count > 50 || count < 1) { context.Response.Write("The array limit 1 to 50"); } else { for (int i = 0; i < count; i++) { if (Utils.subStr(code_list[i], 0, 1) == "6") { market_list.Add(1); } else { market_list.Add(0); } } market = market_list.ToArray(); string connid = RedisHelper.GetValues("connid"); if (connid == "-1" || connid == "") { connid = TradeX.TdxL2Hq_Connect("183.3.223.36", 7709, "srx1314520", "qaz852147wsx", sResult, sErrInfo).ToString(); if (sErrInfo.ToString().Contains("行情连接已满")) { connid = "0"; } RedisHelper.Set <string>("connid", connid, DateTime.Now.AddSeconds(30)); } bool isRet3 = TradeX.TdxL2Hq_GetSecurityQuotes10(market, code_list, ref count, sResult, sErrInfo); if (isRet3 == true) { context.Response.Write(sResult); } else { if (sErrInfo.ToString().Contains("发送数据失败") || sErrInfo.ToString().Contains("无效行情连接")) { TradeX.TdxL2Hq_Disconnect(); context.Response.Write(ConnHq(market, code_list, count)); } else { context.Response.Write(sErrInfo); } } } } //构建异步结果并返回 var result = new WebAsyncResult(cb, context); result.SetComplete(); return(result); }
public UserInfo GetUserCacheShell(int id) { string userRedisKey = "user:info:" + id; return(RedisHelper.CacheShell(userRedisKey, 3600, () => GetUserInfos().FirstOrDefault(r => r.Id == id))); }
public void Delete(int id) { RedisHelper.Del("test1"); }
/// <summary> /// 删除配置文件 /// </summary> /// <returns></returns> public static bool Del() { RedisHelper.Del("Settings"); return(true); }
public void RefreshAccountInfo(AccountInfo accountInfo) { string redisKey = $"{Configs.PlateForm}:AccountInfo:{accountInfo.Id}"; RedisHelper.Set(Configs.RedisIndex_Web, redisKey, accountInfo, TimeSpan.FromDays(1)); }
public async Task <IActionResult> Statistic() { var keys = await RedisHelper.KeysAsync(nameof(PostOnline) + ":*"); var sets = await keys.SelectAsync(async s => (Id : s.Split(':')[1].ToInt32(), Clients : await RedisHelper.HGetAsync <HashSet <string> >(s, "value"))); var ids = sets.Where(t => t.Clients.Count > 0).OrderByDescending(t => t.Clients.Count).Take(10).Select(t => t.Id).ToArray(); var mostHots = await PostService.GetQuery <PostModelBase>(p => ids.Contains(p.Id)).FromCacheAsync().ContinueWith(t => { foreach (var item in t.Result) { item.ViewCount = sets.FirstOrDefault(t => t.Id == item.Id).Clients.Count; } return(t.Result.OrderByDescending(p => p.ViewCount)); }); var postsQuery = PostService.GetQuery(p => p.Status == Status.Published); var mostView = await postsQuery.OrderByDescending(p => p.TotalViewCount).Take(10).Select(p => new PostModelBase() { Id = p.Id, Title = p.Title, ViewCount = p.TotalViewCount }).FromCacheAsync(); var mostAverage = await postsQuery.OrderByDescending(p => p.AverageViewCount).Take(10).Select(p => new PostModelBase() { Id = p.Id, Title = p.Title, ViewCount = (int)p.AverageViewCount }).FromCacheAsync(); return(ResultData(new { mostHots, mostView, mostAverage })); }
public object GetByLuaScript(string script, object obj) { var result = RedisHelper.Eval(script, key: "lock_name", args: obj); return(result); }
public void Post() { RedisHelper helper = new RedisHelper(); helper.AddRandomValuesToHash(); }
public async Task <T> GetAsync <T>(string key) { var result = await RedisHelper.GetAsync <T>(key); return(result); }
/// <summary> /// 文章新增,编辑,由于后期加了一个文章可以有多个标签,一个标签可对应多个文章,就是多对多的关系, /// 所以,这里就需要重新对数据进行处理后,提交数据库 /// </summary> /// <param name="viewModel"></param> /// <param name="id"></param> /// <returns></returns> public override ActionResult Edit(ArticleViewModel viewModel, int id = 0) { if (!ModelState.IsValid) { return(Error(ModelState.Values.FirstOrDefault(u => u.Errors.Count > 0)?.Errors[0].ErrorMessage)); } string tagIds = Request["Tag"].ToString(); List <TagArt> tagArtList = new List <TagArt> { }; if (tagIds.IsNotNullOrEmpty()) { foreach (var i in tagIds.Split(',').Select(u => Convert.ToInt32(u)).ToList()) { tagArtList.Add(new TagArt { TagId = i, AId = id }); } } Article entity; if (id == 0) { entity = Mapper.Map <ArticleViewModel, Article>(viewModel); entity.Create(); entity.TagArts = tagArtList; entity.Archive = DateTime.Now.ToString("yyy年MM月"); _articleRepository.Insert(entity); } else { var tEntityModel = _articleRepository.FindEntity(id); if (tEntityModel == null) { return(Error($"Id为{id}未找到任何类型为{viewModel.GetType().Name}的实体对象")); } entity = Mapper.Map(viewModel, tEntityModel); entity.Modify(id); using (var db = new RepositoryBase().BeginTrans()) { db.Update(entity); db.Delete <TagArt>(u => u.AId == id); db.Insert(tagArtList); db.Commit(); } } //要根据新增或修改的文章类型,来判断是否删除缓存中的数据 if (entity.FId != null) { string itemCode = _itemsDetailRepository.Queryable(u => u.Id == entity.FId).Select(r => r.ItemCode).FirstOrDefault(); if (itemCode != null) { if (itemCode.Equals(CategoryCode.Justfun.ToString())) { RedisHelper.KeyDeleteAsync(string.Format(ConstHelper.App, "JustFun")); } if (itemCode.Equals(CategoryCode.Feelinglife.ToString())) { RedisHelper.KeyDeleteAsync(string.Format(ConstHelper.App, "FellLife")); } } } RedisHelper.KeyDeleteAsync(string.Format(ConstHelper.Article, "GetRecentArticle")); RedisHelper.KeyDelete(string.Format(ConstHelper.Article, "archiveFile")); return(Success()); }
public void Intercept(IInvocation invocation) { try { bool isEnable = Appsettings.CacheEnable; Type returnType = invocation.Method.ReturnType; //获取返回类型 if (isEnable == false || returnType == typeof(void)) //不开启缓存或返回类型为void时,直接执行 { invocation.Proceed(); return; } MethodInfo method = invocation.MethodInvocationTarget ?? invocation.Method; var cacheAttrObj = method.GetCustomAttributes(typeof(CacheableAttribute), false).FirstOrDefault(); //获取当前方法的 CacheableAttribute if (cacheAttrObj is CacheableAttribute cacheAttr) //如果为CacheableAttribute { string cacheKey = GenerateCacheKey(cacheAttr.CacheKey, invocation); //获取自定义缓存键 string cacheValue = RedisHelper.Get(cacheKey); //获取缓存 if (cacheValue != null) //存在缓存数据 { Type[] resultTypes = returnType.GenericTypeArguments; //获取泛型类型的数组,例如Task<T1,T2,T3>中的T1/T2/T3 if (returnType == typeof(Task)) //如果返回类型为Task { invocation.ReturnValue = InterceptAsync(cacheKey, (Task)invocation.ReturnValue); } else if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task <>)) //如果返回类型为Task<> { dynamic d = JsonConvert.DeserializeObject(cacheValue, resultTypes.FirstOrDefault()); //将缓存反序列化为resultTypes.FirstOrDefault()类型 invocation.ReturnValue = Task.FromResult(d); //赋值返回值 } else//否则为同步方法 { invocation.ReturnValue = JsonConvert.DeserializeObject(cacheValue, returnType);//直接赋值返序列化, } return; } invocation.Proceed(); if (returnType == typeof(Task))//如果返回类型为Task { invocation.ReturnValue = InterceptAsync(cacheKey, (Task)invocation.ReturnValue); } else if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task <>)) { invocation.ReturnValue = InterceptAsync(cacheKey, (dynamic)invocation.ReturnValue); } else { RedisHelper.Set(cacheKey, JsonConvert.SerializeObject(invocation.ReturnValue), Appsettings.CacheExpire); } return; } invocation.Proceed(); } catch (Exception) { throw; } }
public RedPocketDetailOM Receive(UserAccount userAccount, string passcode, bool isZH = false) { if (userAccount == null) { throw new SystemErrorException(); } if (string.IsNullOrWhiteSpace(passcode)) { throw new CommonException(Argument_Error, MessageResources.InvalidDataFormat); } if (userAccount.L1VerifyStatus != Entities.Enums.VerifyStatus.Certified) { throw new CommonException(ReasonCode.NOT_VERIFY_LV1, Resources.EMNeedLV1Verfied); } var count = RedisHelper.StringGet(LockDbIndex, string.Format(KeyFormat, userAccount.Id)); if (!string.IsNullOrWhiteSpace(count) && int.Parse(count) >= 10) { var ttl = RedisHelper.KeyTimeToLive(LockDbIndex, string.Format(KeyFormat, userAccount.Id)); if (ttl != null) { var message = ""; var t = ""; try { t = TimeConvert(ttl.Value, isZH); message = string.Format(MessageResources.RedPocket_PassCodeErrorMaxCount, t); } catch (Exception exception) { _log.Error(exception.Message + " " + MessageResources.RedPocket_PassCodeErrorMaxCount + " " + t); } throw new CommonException(MaxError, message); } } var redPocketDAC = new RedPocketDAC(); var redPocket = redPocketDAC.GetByPassCode(passcode); if (redPocket == null) { var errorCount = ErrorCount(userAccount.Id, count, isZH); throw new CommonException(PassCodeError, string.Format(MessageResources.RedPocket_PassCodeError, errorCount, 10 - errorCount)); } if (redPocket.ExpirationDate < DateTime.UtcNow) { var errorCount = ErrorCount(userAccount.Id, count, isZH); throw new CommonException(PassCodeExpired, MessageResources.RedPocket_ReceiveExpired + Environment.NewLine + string.Format(MessageResources.RedPocket_PassCodeError, errorCount, 10 - errorCount)); } var crypto = new CryptocurrencyDAC().GetByCode(redPocket.CryptoCode); if (!crypto.Status.HasFlag(Foundation.Entities.Enum.CryptoStatus.RedPocket) || crypto.Enable == 0) { throw new CommonException(ReasonCode.CURRENCY_FORBIDDEN, MessageResources.CurrencyForbidden); } var om = new RedPocketDetailOM(); var redPocketReceiveDAC = new RedPocketReceiverDAC(); var hasReceive = redPocketReceiveDAC.HasReceive(userAccount.Id, redPocket.Id); if (redPocket.Status == RedPocketStatus.Actived && hasReceive == null) { var userWalletDAC = new UserWalletDAC(); var userWalletStatementDAC = new UserWalletStatementDAC(); var uwComponent = new UserWalletComponent(); var userTransactionDAC = new UserTransactionDAC(); var wallet = userWalletDAC.GetByCryptoCode(userAccount.Id, redPocket.CryptoCode); if (wallet == null) { wallet = uwComponent.GenerateWallet(userAccount.Id, redPocket.CryptoCode); } var min = crypto.DecimalPlace == 8 ? 0.00000001M : crypto.DecimalPlace == 6 ? 0.000001M : 0.00000001M; var n = crypto.DecimalPlace == 8 ? 100000000 : crypto.DecimalPlace == 6 ? 1000000 : 100000000; var amount = GetRandomMoney(redPocket, min, n); var priceDAC = new PriceInfoDAC(); var price = priceDAC.GetPriceByName("USD", crypto.Code); var fiatAmount = price * amount; using (var scope = new TransactionScope()) { try { var redPocketReceiver = new RedPocketReceiver { PocketId = redPocket.Id, AccountId = userAccount.Id, SendAccountId = redPocket.AccountId, CryptoCode = redPocket.CryptoCode, Amount = amount, Timestamp = DateTime.UtcNow, IsBestLuck = redPocket.Count == 1, OrderNo = IdentityHelper.OrderNo(), FiatAmount = fiatAmount <= 0 ? 0M : Math.Round(fiatAmount, 8) }; var id = redPocketReceiveDAC.Insert(redPocketReceiver); userTransactionDAC.Insert(new UserTransaction { Id = Guid.NewGuid(), AccountId = redPocketReceiver.AccountId, CryptoId = redPocket.CryptoId, CryptoCode = redPocket.CryptoCode, Type = UserTransactionType.ReceiveRedPocket, DetailId = id.ToString(), Status = (byte)redPocket.Status, Timestamp = redPocketReceiver.Timestamp, Amount = redPocketReceiver.Amount, OrderNo = redPocketReceiver.OrderNo }); userWalletDAC.Increase(wallet.Id, amount); userWalletStatementDAC.Insert(new UserWalletStatement { WalletId = wallet.Id, Balance = wallet.Balance + amount, Amount = amount, FrozenAmount = 0, FrozenBalance = wallet.FrozenBalance, Action = "Receive Red Pocket", Timestamp = DateTime.UtcNow }); redPocketDAC.UpdateRemain(redPocket.Id, amount); if (redPocket.RemainCount == 0) { redPocketDAC.UpdateStatus(redPocket.Id, RedPocketStatus.Complate); userTransactionDAC.UpdateStatus(UserTransactionType.PushRedPocket, redPocket.Id.ToString(), redPocket.AccountId, (byte)RedPocketStatus.Complate); if (redPocket.Count > 1) { redPocketReceiveDAC.UpdateBestLuck(redPocket.Id); } } scope.Complete(); } catch (Exception ex) { _log.Error(ex); throw new CommonException(); } } om.SelfAmount = amount.ToString(); om.ReceiveStatus = ReceiveStatusEnum.Receive; om.HasExpried = false; redPocket.Balance -= amount; } else { if (hasReceive != null) { om.ReceiveStatus = ReceiveStatusEnum.HasReceive; om.SelfAmount = hasReceive.Amount.ToString(); } else { om.ReceiveStatus = ReceiveStatusEnum.None; om.SelfAmount = string.Empty; } } var account = new UserAccountComponent().GetById(redPocket.AccountId); om.Message = redPocket.Message; om.SnederNickname = account.Nickname; om.TotalAmount = redPocket.Amount.ToString(); om.TotalCount = redPocket.Count; om.CryptoCode = redPocket.CryptoCode; om.ReceiveAmount = (redPocket.Amount - redPocket.Balance).ToString(); om.ReceiveCount = redPocket.Count - redPocket.RemainCount; om.Id = redPocket.Id; om.HasExpried = redPocket.ExpirationDate < DateTime.UtcNow; om.HasSelfSned = redPocket.AccountId == userAccount.Id; return(om); }
public async Task ReleaseRoom(int roomId) { await RedisHelper.DelAsync(RedisConstants.HKeyRedis_Room, roomId.ToString()); await RedisHelper.RPushAsync(RedisConstants.LKeyRedis_RoomId, roomId); }
public BaseController(RedisHelper client) { _redisUser = client.GetUserDB(); }
public async Task <bool> RoomExist(int roomId) { return(await RedisHelper.HExistsAsync(RedisConstants.HKeyRedis_Room, roomId.ToString())); }
public void ThrowForInvalidDatabaseIndex() { new RedisLockExtension(RedisHelper.GetConnection(), -10); }
public void String() { var redis = new RedisHelper(); redis.Set<string>("name", "laowang"); string userName = redis.Get<string>("name"); Console.WriteLine(userName); //访问次数 redis.Set<int>("IpAccessCount", 0); //次数递增 redis.Incr("IpAccessCount"); Console.WriteLine(redis.Get<int>("IpAccessCount")); }
public void SortSet() { //应用场景: //以某个条件为权重,比如按顶的次数排序. //ZREVRANGE命令可以用来按照得分来获取前100名的用户,ZRANK可以用来获取用户排名,非常直接而且操作容易。 //Redis sorted set的使用场景与set类似,区别是set不是自动有序的,而sorted set可以通过用户额外提供一个优先级(score)的参数来为成员排序,并且是插入有序的,即自动排序。 //比如:twitter 的public timeline可以以发表时间作为score来存储,这样获取时就是自动按时间排好序的。 //比如:全班同学成绩的SortedSets,value可以是同学的学号,而score就可以是其考试得分,这样数据插入集合的,就已经进行了天然的排序。 //另外还可以用Sorted Sets来做带权重的队列,比如普通消息的score为1,重要消息的score为2,然后工作线程可以选择按score的倒序来获取工作任务。让重要的任务优先执行。 var redis = new RedisHelper(); #region "有序Set操作" redis.AddItemToSortedSet("SA", "B", 2); redis.AddItemToSortedSet("SA", "C", 1); redis.AddItemToSortedSet("SA", "D", 5); redis.AddItemToSortedSet("SA", "E", 3); redis.AddItemToSortedSet("SA", "F", 4); //有序集合降序排列 Console.WriteLine("\n有序集合降序排列"); redis.GetAllItemsFromSortedSetDesc("SA").ForEach(e => Console.Write(e + ",")); Console.WriteLine("\n有序集合升序序排列"); redis.GetAllItemsFromSortedSet("SA").ForEach(e => Console.Write(e + ",")); redis.AddItemToSortedSet("SB", "C", 2); redis.AddItemToSortedSet("SB", "F", 1); redis.AddItemToSortedSet("SB", "D", 3); Console.WriteLine("\n获得某个值在有序集合中的排名,按分数的升序排列"); Console.WriteLine(redis.GetItemIndexInSortedSet("SB", "D")); Console.WriteLine("\n获得有序集合中某个值得分数"); Console.WriteLine(redis.GetItemScoreInSortedSet("SB", "D")); Console.WriteLine("\n获得有序集合中,某个排名范围的所有值"); redis.GetRangeFromSortedSet("SA", 0, 3).ForEach(e => Console.Write(e + ",")); #endregion }
public void ThrowForNullChannel() { new RedisLockExtension(RedisHelper.GetConnection(), channelPrefix: null); }
public ActionResult <string> Get() { return(RedisHelper.Get("test1")); }
public ActionResult PushMerge(PostMergeRequestCommand dto) { if (RedisHelper.Get("code:" + dto.ModifierEmail) != dto.Code) { return(ResultData(null, false, "验证码错误!")); } var post = PostService.GetById(dto.PostId) ?? throw new NotFoundException("文章未找到"); var diff = new HtmlDiff.HtmlDiff(post.Content.RemoveHtmlTag(), dto.Content.RemoveHtmlTag()); if (post.Title.Equals(dto.Title) && !diff.Build().Contains(new[] { "diffmod", "diffdel", "diffins" })) { return(ResultData(null, false, "内容未被修改!")); } #region 合并验证 if (PostMergeRequestService.Any(p => p.ModifierEmail == dto.ModifierEmail && p.MergeState == MergeStatus.Block)) { return(ResultData(null, false, "由于您曾经多次恶意修改文章,已经被标记为黑名单,无法修改任何文章,如有疑问,请联系网站管理员进行处理。")); } if (post.PostMergeRequests.Any(p => p.ModifierEmail == dto.ModifierEmail && p.MergeState == MergeStatus.Pending)) { return(ResultData(null, false, "您已经提交过一次修改请求正在待处理,暂不能继续提交修改请求!")); } #endregion #region 直接合并 if (post.Email.Equals(dto.ModifierEmail)) { var history = post.Mapper <PostHistoryVersion>(); Mapper.Map(dto, post); post.PostHistoryVersion.Add(history); post.ModifyDate = DateTime.Now; return(PostService.SaveChanges() > 0 ? ResultData(null, true, "你是文章原作者,无需审核,文章已自动更新并在首页展示!") : ResultData(null, false, "操作失败!")); } #endregion var merge = post.PostMergeRequests.FirstOrDefault(r => r.Id == dto.Id && r.MergeState != MergeStatus.Merged); if (merge != null) { Mapper.Map(dto, merge); merge.SubmitTime = DateTime.Now; merge.MergeState = MergeStatus.Pending; } else { merge = Mapper.Map <PostMergeRequest>(dto); post.PostMergeRequests.Add(merge); } var b = PostService.SaveChanges() > 0; if (!b) { return(ResultData(null, b, b ? "您的修改请求已提交,已进入审核状态,感谢您的参与!" : "操作失败!")); } RedisHelper.Expire("code:" + dto.ModifierEmail, 1); MessageService.AddEntitySaved(new InternalMessage() { Title = $"来自【{dto.Modifier}】的文章修改合并请求", Content = dto.Title, Link = "#/merge/compare?id=" + merge.Id }); var content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/merge-request.html").Replace("{{title}}", post.Title).Replace("{{link}}", Url.Action("Index", "Dashboard", new { }, Request.Scheme) + "#/merge/compare?id=" + merge.Id); BackgroundJob.Enqueue(() => CommonHelper.SendMail("博客文章修改请求:", content, CommonHelper.SystemSettings["ReceiveEmail"])); return(ResultData(null, b, b ? "您的修改请求已提交,已进入审核状态,感谢您的参与!" : "操作失败!")); }
public ActionResult About() { ViewData.Model = Session["UserAgent"]; ViewBag.Message = "Your application description page."; RedisHelper redis = new RedisHelper(1); #region String string str = "123"; Demo demo = new Demo() { Id = 1, Name = "123" }; var resukt = redis.StringSet("redis_string_test", str); var str1 = redis.StringGet("redis_string_test"); redis.StringSet("redis_string_model", demo); var model = redis.StringGet<Demo>("redis_string_model"); for (int i = 0; i < 10; i++) { redis.StringIncrement("StringIncrement", 2); } for (int i = 0; i < 10; i++) { redis.StringDecrement("StringIncrement"); } redis.StringSet("redis_string_model1", demo, TimeSpan.FromSeconds(10)); #endregion String #region List for (int i = 0; i < 10; i++) { redis.ListRightPush("list", i); } for (int i = 10; i < 20; i++) { redis.ListLeftPush("list", i); } var length = redis.ListLength("list"); var leftpop = redis.ListLeftPop<string>("list"); var rightPop = redis.ListRightPop<string>("list"); var list = redis.ListRange<int>("list"); #endregion List #region Hash redis.HashSet("user", "u1", "123"); redis.HashSet("user", "u2", "1234"); redis.HashSet("user", "u3", "1235"); var news = redis.HashGet<string>("user", "u2"); #endregion Hash #region 发布订阅 redis.Subscribe("Channel1"); for (int i = 0; i < 10; i++) { redis.Publish("Channel1", "msg" + i); if (i == 2) { redis.Unsubscribe("Channel1"); } } #endregion 发布订阅 #region 事务 var tran = redis.CreateTransaction(); tran.StringSetAsync("tran_string", "test1"); tran.StringSetAsync("tran_string1", "test2"); bool committed = tran.Execute(); #endregion 事务 #region Lock var db = redis.GetDatabase(); RedisValue token = Environment.MachineName; if (db.LockTake("lock_test", token, TimeSpan.FromSeconds(10))) { try { //TODO:开始做你需要的事情 Thread.Sleep(5000); } finally { db.LockRelease("lock_test", token); } } #endregion Lock return View(); }