public FeedController() { var connectionString = ConfigurationManager.ConnectionStrings["AssignifyItDatabase"].ConnectionString; var redisUrl = ConfigurationManager.AppSettings["REDISCLOUD_URL"]; var redisManager = new RedisManager(redisUrl); var query = new DailyTextManagerQuery(connectionString); _dailyTextManager = new DailyTextManager(query, redisManager); }
/// <summary> /// 插入和读取字符串类型 /// </summary> static void PutString() { RedisManager rm = new RedisManager(); rm.InsertString<string>("mykey", " money"); var value = rm.GetString("mykey"); Console.WriteLine(value); //Console.ReadLine(); }
public void Redis测试() { string key = "REDIS_TEST_KEY"; string redisValue="redis测试"; ICacheManager cache = new RedisManager(); cache.Set(key, redisValue, 60); string value = cache.Get<string>(key); Assert.AreEqual(value, redisValue); cache.Remove(key); }
public List <Active> topics(string tab, int id) { List <Active> activelist = ActiveService.GetActiveList(tab, id); IRedisClient redisClient = RedisManager.GetClient(); redisClient.Set <List <Active> >("active", activelist); redisClient.Save(); redisClient.Dispose(); return(activelist); }
/// <summary> /// 构造器 /// </summary> public RedisStoreProvider() { this._clientsManager = RedisManager.CreateClientsManager(); //获取会话Id string sessionId = WebConfigSetting.CurrentSessionId.ToString(); //实例化RedisClient this._redisClient = this._clientsManager.GetClient(); this._redisTypedClient = this._redisClient.As <Event>(); this._table = this._redisTypedClient.Lists[sessionId]; }
public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; string content = dataMap.GetString("MarketingRefreshInfo"); #if(Local!=true) RedisManager.Publish("MarketingRefresh", content); #endif #if(Local) StoreManager.PubEvent("MarketingRefresh", content); #endif }
public async Task <ActionResult> Category(string id = "") { var cateListTemp = RedisManager.GetItem <List <Category> >("categories"); if (cateListTemp == null) { cateListTemp = await _categoryRepository.GetAll(); if (cateListTemp != null && cateListTemp.Any()) { RedisManager.SetItem("categories", cateListTemp, new TimeSpan(0, Settings.Config.CacheExpired, 0)); } } if (id != "" && id != "other" && !cateListTemp.Select(t => t.Alias).Contains(id)) { var error = new Elmah.Error(new Exception("分类alias:" + id + " 不存在!"), System.Web.HttpContext.Current) { StatusCode = 404 }; Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(error); return(View("Error404")); } var cateList = new List <CategoryBar>(); cateList.Add(new CategoryBar { Alias = string.Empty, CateName = "全部分类", Img = "/Content/Img/全部分类.svg" //PostCount = await _postRepository.GetPostCountByCate(string.Empty) }); foreach (var category in cateListTemp) { cateList.Add(new CategoryBar { Alias = category.Alias, CateName = category.CateName, Img = "/Content/Img/通用分类.svg", Link = category.Link //PostCount = await _postRepository.GetPostCountByCate(category.UniqueId) }); } cateList.Add(new CategoryBar { Alias = "other", CateName = "未分类", Img = "/Content/Img/未分类.svg" //PostCount = await _postRepository.GetPostCountByCate("other") }); ViewBag.CateList = cateList; ViewBag.CateAlias = id; return(View("Category")); }
public void Execute(IJobExecutionContext context) { JobDataMap dataMap = context.JobDetail.JobDataMap; string content = dataMap.GetString("MarketingRefreshInfo"); #if(Local!=true) RedisManager.Publish("RefreshHostedMarketing", content); #endif #if(Local) StoreManager.PubEvent("RefreshHostedMarketing", content); #endif File.AppendAllText(@"C:\tts.x", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + Environment.NewLine); }
public async Task Test_Get_Async_Val() { var redisManager = new RedisManager(_options); var key = Guid.NewGuid().ToString(); var result = redisManager.GetDatabase().StringSetAsync(key, JsonConvert.SerializeObject("Test Data")).Result; var val = await redisManager.GetAsync <string>(key); Assert.AreEqual("Test Data", val); }
/// <summary> /// 设置缓存 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void SetCache <T>(string key, T value) { try { RedisManager.Set(key, value); } catch (Exception ex) { //FileLog.WriteLog("StorageRedis:Set(string key, object value),error:" + JsonConvert.SerializeObject(ex)); throw ex; } }
/// <summary> /// 验证用户登录 /// </summary> /// <param name="userParams">登录参数</param> /// <returns></returns> public static LoginResult Login(LoginParams userParams, string deviceSn, bool inTestMode = false, bool isLock = false) { var dataAdapter = DataAdapterFactory.Factory(MachinesSettings.Mode, userParams.StoreId, userParams.MachineSn, userParams.CompanyId, deviceSn); var userInfo = dataAdapter.GetUser(userParams.Account); if (userInfo == null) { throw new LoginExecption("401", "账号错误!"); } if (userInfo.LoginPwd != MD5.MD5Encrypt(userParams.Password)) { throw new LoginExecption("401", "密码错误!"); } //本店角色(1:店长、2:营业员、3:收银员、4:数据维护),格式:门店ID,角色ID|门店ID,角色ID if (!inTestMode && !(VerfyOperateAuth(userInfo, dataAdapter.StoreId, StoreOperateAuth.Cashier) || VerfyOperateAuth(userInfo, dataAdapter.StoreId, StoreOperateAuth.DataManager))) { throw new LoginExecption("402", "非销售员或数据维护员不允许登录销售!"); } var key = KeyFactory.MachineKeyFactory(userParams.CompanyId, userParams.StoreId, userParams.MachineSn, deviceSn); var machineInfo = new MachineInformation() { CashierName = userInfo.FullName, CashierOperateAuth = userInfo.OperateAuth, CashierUid = userInfo.UID, CashierUserCode = userInfo.UserCode, StoreName = userInfo.StoreName, StoreId = userParams.StoreId, MachineSn = userParams.MachineSn, CompanyId = userParams.CompanyId, InTestMode = inTestMode, DeviceSn = deviceSn }; onlineCache.Set(key, machineInfo); #if (Local != true) RedisManager.Publish("SyncOnlineCache", JsonConvert.SerializeObject(machineInfo)); #endif #if (Local) StoreManager.PubEvent("SyncOnlineCache", JsonConvert.SerializeObject(machineInfo)); #endif if (!isLock) { ShoppingCartFactory.Factory(userParams.StoreId, userParams.MachineSn, userParams.CompanyId, deviceSn, true); } return(new LoginResult() { FullName = userInfo.FullName, OperateAuth = userInfo.OperateAuth, UserCode = userInfo.UserCode, StoreName = userInfo.StoreName }); }
/// <summary> /// Loads the registrations. /// </summary> /// <param name="builder">The container builder.</param> protected override void Load(ContainerBuilder builder) { builder.Register(cc => { RedisManager redisManager = new RedisManager(); redisManager.Connect(); return(redisManager); }) .As <IDistributedMemoryManager>() .SingleInstance(); builder.RegisterType <TaskManager>().As <ITaskManager>().SingleInstance(); }
public static void Subscribe() { RedisManager.Subscribe("RefreshProductCache", (channel, info) => { try { // Console.WriteLine(info); var qrefresh = JsonConvert.DeserializeObject <IEnumerable <ObjectModels.DTOs.MemoryCacheRefreshQuery> >(info); ProductCache.RefreshProduct(qrefresh); } catch { } }); }
/// <summary> /// 获取所有的HashKeys /// </summary> /// <param name="hashId"></param> /// <returns></returns> public List <string> GetHashKeys(string hashId) { using (var redisClient = RedisManager.GetClient()) { var items = redisClient.GetAllEntriesFromHash(hashId); if (items == null || items.Count == 0) { return(new List <string>()); } return(items.Keys.ToList()); } }
public UserController( ILogger <UserController> logger, IUserQueries userQueries, IConfiguration _configuration, IOptions <DomainConfig> options, RedisManager redisManager) { _logger = logger; _userQueries = userQueries; Configuration = _configuration; domainConfig = options.Value; _redisManager = redisManager; }
public void SendVerifyMessage(int cid) { var customerInfo = _customerDal.Find <CustomerInfoEntity>(cid); var mobile = customerInfo.Mobile; Random rd = new Random(); var r = rd.Next(1000, 9999).ToString(); string msg = "验证码:" + r + " 有效期10分钟,请输入验证码完成重新绑定手机。"; string sendType = "手工";//"手机验证码发送"; RedisManager.Set(r.ToString(), CacheKeyEnum.CustomerMobileVerifyCode + mobile, new TimeSpan(0, 15, 0)); SMSHelper.SMSSendMessage(mobile, msg, sendType); }
/// <summary> /// 获取缓存(泛型) /// </summary> /// <param name="key"></param> public T GetCache <T>(string key) { try { return(RedisManager.Get <T>(key)); } catch (Exception ex) { //FileLog.WriteLog("StorageRedis:Get<T>(string key),error:" + JsonConvert.SerializeObject(ex)); //return default(T); throw ex; } }
private List <X1ReturnDeviceModel> GetDevListFromCache(string hostId) { using (var client = RedisManager.GetClient()) { string cacheKey = "AliGenie_" + hostId; var templss = client.Get <List <X1ReturnDeviceModel> >(cacheKey); if (templss == null) { templss = new List <X1ReturnDeviceModel>(); } return(templss); } }
public ActionResult GetRedisTest([FromQuery] string msg) { //DMS.Redis.RedisManager redisManager = new DMS.Redis.RedisManager(3); //redisManager.ListRightPush("key123", "right11111"); #region 发布 RedisManager redisManager5 = new RedisManager(5); // var keys = redisManager5.HashKeys<object>("room1"); var a = redisManager5.Publish("queue_roomvisirecord", msg); #endregion return(Ok("")); }
public static string ReturnMessage(string postStr) { var responseContent = ""; try { var xmldoc = new XmlDocument(); xmldoc.LoadXml(postStr); var msgId = xmldoc.SelectSingleNode("/xml/MsgId")?.InnerText; if (msgId.IsNullOrEmpty()) { var firewall = RedisManager.GetFirewallClient($"wechatMsgFirewall-{msgId}", TimeSpan.FromSeconds(2)); if (!firewall.Hit()) { return(string.Empty); } } var msgType = xmldoc.SelectSingleNode("/xml/MsgType"); if (msgType != null) { switch (msgType.InnerText) { case "event": responseContent = EventHandle(xmldoc); //事件处理 break; case "text": responseContent = TextMsgHandle(xmldoc); //接受文本消息处理 break; case "image": responseContent = ImageMsgHandle(xmldoc); //图片消息 break; case "voice": responseContent = VoiceMsgHandleAsync(xmldoc); //语音消息 break; default: break; } } } catch (Exception ex) { Logger.Error("发生异常,异常信息:" + ex.Message + ex.StackTrace); } return(responseContent); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //log4net init LogHelper.LogInit(new ILogHelperProvider[] { new SentryLogHelperProvider() }); //Register filters FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); #region DependenceInjection var builder = new ContainerBuilder(); //RegisterAssemblyModules builder.RegisterAssemblyModules(BuildManager.GetReferencedAssemblies().Cast <Assembly>().ToArray()); //ReservationDbContext builder.RegisterType <Models.ReservationDbContext>().SingleInstance(); //register controllers builder.RegisterControllers( typeof(HomeController).Assembly, typeof(AdminLogic.Controllers.HomeController).Assembly, typeof(WechatAPI.Controllers.HomeController).Assembly); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); // set to my own resolver WeihanLi.Common.DependencyResolver.SetDependencyResolver( new WeihanLi.Common.AutofacDependencyResolver(container)); #endregion DependenceInjection // redis config RedisManager.AddRedisConfig(option => { option.CachePrefix = "ActivityReservation"; option.ChannelPrefix = "ActivityReservation"; }); //register system settings SystemSettingsConfig.RegisterSystemSettings(); }
public ActionResult SaveAll() { using (var redisClient = RedisManager.GetClient()) { var user = redisClient.GetTypedClient <User>(); #region if (user.GetAll().Count > 0) { user.DeleteAll(); } var qiujialong = new User { Id = user.GetNextSequence(), Name = "qiujialong", Job = new Job { Position = ".NET" } }; var chenxingxing = new User { Id = user.GetNextSequence(), Name = "chenxingxing", Job = new Job { Position = ".NET" } }; var luwei = new User { Id = user.GetNextSequence(), Name = "luwei", Job = new Job { Position = ".NET" } }; var zhourui = new User { Id = user.GetNextSequence(), Name = "zhourui", Job = new Job { Position = "Java" } }; #endregion var usertoStore = new List <User> { qiujialong, chenxingxing, luwei, zhourui }; user.StoreAll(usertoStore); return(Content("目前共有:" + user.GetAll().Count.ToString() + "人!")); } }
public async Task <ViewResult> Item(string id) { if (id.Equals("about", StringComparison.CurrentCultureIgnoreCase)) { var configSettings = new ConfigSettings(); var config = new AboutConfig(configSettings, "About", Server.MapPath("~/Settings")); config.Load(); return(View("About", config)); } if (id.Equals("guestbook", StringComparison.CurrentCultureIgnoreCase)) { return(View("Guestbook")); } var cacheKey = "post_" + id; var post = RedisManager.GetItem <Post>(cacheKey); if (post == null) { post = await _postRepository.GetPostByAlias(id); if (post != null) { RedisManager.SetItem(cacheKey, post, new TimeSpan(0, Settings.Config.CacheExpired, 0)); } } if (post != null) { var item = new PostItem { UniqueId = post.UniqueId, Title = post.Title, CategoryAlias = post.CategoryAlias, CateName = await _categoryRepository.GetNameByAlias(post.CategoryAlias), CreateTimeStr = post.CreateTime.ToString("yy-MM-dd HH:mm"), ViewCount = post.ViewCount, LabelList = JsonConvert.DeserializeObject <List <LabelShow> >(post.Labels).Select(t => t.Text).ToList(), Summary = post.Summary, Content = post.Content }; return(View(item)); } else { var error = new Elmah.Error(new Exception("文章id:" + id + " 不存在!"), System.Web.HttpContext.Current) { StatusCode = 404 }; Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(error); return(View("Error404")); } }
private void redisOpen_Click(object sender, EventArgs e) { var address = txt_address.Text?.Trim().Split(':'); var ip = address[0]; var port = address.Length >= 2 ? address[1] : "6379"; var dbindex = address.Length >= 3 ? address[2] : "1"; var config = $"{ip}:{port},allowAdmin=true,password=,syncTimeout=15000,defaultdatabase={dbindex}"; var initialTime = DateTime.Now; redis = new RedisManager(config, int.Parse(dbindex)); var timeConsuming = (DateTime.Now - initialTime).TotalMilliseconds; AppendText($"连接成功\t\t\t\t耗时:{timeConsuming}ms"); }
public async Task StringCounterExpiryTest() { var counterName = nameof(StringCounterExpiryTest); var counter = RedisManager.GetCounterClient(counterName, TimeSpan.FromSeconds(5)); await Task.WhenAll(Enumerable.Range(0, 5).Select(x => counter.IncreaseAsync())); Assert.Equal(5, counter.Count()); await Task.Delay(TimeSpan.FromSeconds(5)); Assert.Equal(1, counter.Increase()); await Task.Delay(TimeSpan.FromSeconds(5)); Assert.False(RedisManager.GetCommonRedisClient(RedisDataType.Counter).KeyExists(counterName)); }
private static void UpdateUserToRedis() { Dictionary <string, string> redisUser = new Dictionary <string, string>(); foreach (string key in mapUser.Keys) { string userInfo = getJsonByObject(mapUser[key]); redisUser.Add(key, userInfo); } var client = RedisManager.GetClient(); client.HMSet(redisUserInfoKey, redisUser); }
/// <summary> /// 批量插入数据 /// </summary> /// <param name="lstRedisEntities"></param> /// <returns></returns>x public bool BatchInsertRedisData <T>(List <T> lstRedisEntities) { if (lstRedisEntities == null || lstRedisEntities.Count == 0) { return(false); } using (var redisClient = RedisManager.GetClient()) { var dropListData = redisClient.GetTypedClient <T>(); dropListData.StoreAll(lstRedisEntities); return(true); } }
/// <summary> /// Adds the specified key and object to the cache. /// </summary> public virtual void Set(string key, object data, TimeSpan expire) { RedisManager.PrepareDataBase(_db => { var res = new CacheResult <object>() { Success = true, Result = data }; var entryBytes = this.Serialize(res); _db.StringSet(key, entryBytes, expire); return(true); }, CACHE_DB); }
public void DictionaryTest() { var dictionary = RedisManager.GetDictionaryClient <string, int>("testDictionary", TimeSpan.FromMinutes(1)); Assert.Equal(0, dictionary.Count()); Assert.False(dictionary.Exists("chinese")); dictionary.Add("math", 80); dictionary.Add("English", 60); Assert.True(dictionary.Exists("math")); Assert.Equal(80, dictionary.GetOrAdd("math", 20)); Assert.Equal(2, dictionary.Count()); Assert.False(dictionary.Exists("chinese")); Assert.True(dictionary.Remove("English")); }
public void MainTest() { var testSetKey = "testSet"; var setClient = RedisManager.GetSetClient <string>(testSetKey); Assert.Equal(0, setClient.Length()); setClient.Add(new[] { "Michael", "Kangkang", "Kangkang" }); Assert.Equal(2, setClient.Length()); Assert.True(setClient.Remove("Kangkang")); Assert.Equal(1, setClient.Length()); var commonClient = RedisManager.GetCommonRedisClient(RedisDataType.Set); Assert.True(commonClient.KeyDelete(testSetKey)); }
public string GetValueByCache(string key) { try { using (var redisClient = RedisManager.GetClient()) { return(redisClient.Get <string>(key)); } } catch (Exception) { } return(""); }
/// <summary> /// 通过Redis键获取实体对象 /// </summary> /// <param name="key"></param> /// <param name="isRemove"></param> /// <param name="type"></param> /// <returns></returns> public static dynamic GetEntityFromRedis(string key, bool isRemove, Type type = null) { string typeName; string asmName; bool isEntityType; string redisKey; string entityKey = GetEntityTypeFromKey(key, out typeName, ref type, out asmName, out isEntityType, out redisKey); dynamic entity = null; RedisManager.Process(client => { if (isEntityType) { var data = client.Get <byte[]>(redisKey); if (data != null && type != null) { entity = ProtoBufUtils.Deserialize(data, type); } } else { var data = client.Get <byte[]>(redisKey); if (data != null && type != null) { var dict = (IDictionary)ProtoBufUtils.Deserialize(data, type); entity = dict[entityKey]; } } if (isRemove && entity == null && type != null) { string setId = (isEntityType ? typeName : redisKey) + ":remove"; var data = client.Get <byte[]>(setId); if (data != null) { var dict = (IDictionary)ProtoBufUtils.Deserialize(data, type); entity = dict[entityKey]; dict.Remove(entityKey); if (dict.Count > 0) { client.Set(setId, ProtoBufUtils.Serialize(dict)); } else { client.Remove(setId); } } } }); return(entity); }
public JsonResult AddReservationPeriod(ReservationPeriod model) { if (model.PlaceId == Guid.Empty) { return(Json("预约活动室不能为空")); } if (model.PeriodTitle.IsNullOrWhiteSpace()) { return(Json("预约时间段不能为空")); } if (!_reservationPlaceHelper.Exist(p => p.PlaceId == model.PlaceId)) { return(Json("活动室不存在")); } using (var redLock = RedisManager.GetRedLockClient($"reservation_{model.PlaceId:N}_periods")) { if (redLock.TryLock()) { if (_reservationPeriodHelper.Any(builder => builder .IgnoreQueryFilters() .WithPredict(p => p.PeriodIndex == model.PeriodIndex && p.PlaceId == model.PlaceId && p.PeriodId != model.PeriodId) ) ) { return(Json("排序重复,请修改")); } model.PeriodId = Guid.NewGuid(); model.CreateBy = UserName; model.CreateTime = DateTime.UtcNow; model.UpdateBy = UserName; model.UpdateTime = DateTime.UtcNow; var result = _reservationPeriodHelper.Insert(model); if (result > 0) { OperLogHelper.AddOperLog($"创建预约时间段{model.PeriodId:N},{model.PeriodTitle}", OperLogModule.ReservationPlace, UserName); } return(Json(result > 0 ? "" : "创建预约时间段失败")); } else { return(Json("系统繁忙,请稍后重试")); } } }
/// <summary> /// 插入和读取列表类型 /// </summary> static void PutList() { List<string> lstWeek = new List<string>(); lstWeek.Add("Monday"); lstWeek.Add("Wedday"); lstWeek.Add("Sunday"); RedisManager rm = new RedisManager(); rm.InsertList<string>("mylist", lstWeek); string mstr = rm.GetListItem("mylist", 0); Debug.Assert("Monday"== mstr, "it's wrong"); List<string> lst = rm.RangeList("mylist", 0, 1).ToList(); Console.WriteLine(lst.Count); Console.ReadLine(); }
static void PutXmlString() { XDocument xDoc = XDocument.Load(new System.IO.StreamReader("dt_sample.xml")); string s = xDoc.ToString(); RedisManager rm = new RedisManager(); rm.InsertString("myxmlstring", s); string sCached = rm.GetString("myxmlstring"); //deleted rm.DeleteXElement("myxmlstring", 2); string sDel = rm.GetXDocument("myxmlstring").ToString(); //inserted string insXml = "<DataSet><DataTable><DataRow><ID>2</ID><cod>P</cod><txt>涤</txt><supID>1</supID><suptxt>面料</suptxt><supcod>F</supcod><lvl>2</lvl><dir>1</dir></DataRow></DataTable></DataSet>"; rm.SaveXElement("myxmlstring", 2, insXml); string sCachedIns = rm.GetXDocument("myxmlstring").ToString(); }
/// <summary> /// 初始化提供程序。 /// </summary> /// <param name="name">该提供程序的友好名称。</param> /// <param name="config">名称/值对的集合,表示在配置中为该提供程序指定的、提供程序特定的属性。</param> public override void Initialize(string name, NameValueCollection config) { if(string.IsNullOrWhiteSpace(name)) name = "AspNetSession"; var address = config["address"]; var password = config["password"]; var defaultAddress = RedisManager.DefaultAddress; if(address != null) { var sp = address.Split(':'); if(sp.Length != 2) throw new ArgumentException("非法的 Redis 的连接地址 {0}。".Fmt(address)); defaultAddress = new Net.SocketInfo(sp[0], int.Parse(sp[1])); } this._redisManager = new RedisManager(defaultAddress, password); var sessionConfig = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState"); this._sessionTimeout = sessionConfig.Timeout; base.Initialize(name, config); }