public IActionResult Login(string account, string password) { var isExist = _user.UserLogin(account, password, out var userInfo); //用户不存在 if (!isExist) { return(new JsonResult(JsonConvert.SerializeObject(new { StatusCode = 200, Status = ReturnStatus.Fail, Msg = "用户名或密码错误,请重新输入" }))); } var token = JWTTokenHelper.JwtEncrypt(new TokenModelJwt() { UserId = userInfo.Id, Level = "" }, this._jwtTokenOptions); using (RedisStringService service = new RedisStringService()) { service.Set <T_Sys_User>("Bearer " + token, userInfo); } return(new JsonResult(new ReturnResultModel() { StatusCode = 200, Status = ReturnStatus.Success, Data = token, Msg = "登录成功" })); }
/// <summary> /// 确认器,读取缓存状态,半秒读取一次,共读取3秒左右,没反应就返回失败 /// </summary> /// <param name="cachekey"></param> /// <param name="ok"></param> /// <returns></returns> public static bool MacResult(string cachekey, string st) { using (RedisStringService service = new RedisStringService()) { bool state = false; int i = 0; while (i < 30)//6s,次数限制redis { i++; Thread.Sleep(200); //读取缓存状态 string BusSwitchMac = service.Get(cachekey); if (!string.IsNullOrEmpty(BusSwitchMac)) { BusSwitchMac = BusSwitchMac.Replace("\"", ""); if (BusSwitchMac == st) { log.Debug($"设备状态改变成功! cachekey:{cachekey}!轮询次数: {i}"); state = true; break; } } else { log.Debug($"设备状态改变失败! cachekey:{cachekey} 不存在!请按一下设备"); } } return(state); } }
public HomeController(ILogger <HomeController> logger, ILogoService logo, IBaseCache cache, RedisStringService stringService, IRabbitManage mq) { _Logger = logger; _Logo = logo; _BaseCache = cache; _StringService = stringService; _RabbitMQ = mq; }
public void TestRedis() { using (var service = new RedisStringService()) { service.Set("RedisStringService_key1", "RedisStringService_value1"); service.Get("RedisStringService_key1"); } }
public IHttpActionResult Logout() { var token = ActionContext.Request.Headers.GetValues(Contants.TokenName).FirstOrDefault(); //清空 HttpContext.Current.GetOwinContext().Set <UserInfo>(nameof(UserInfo), null); using (var service = new RedisStringService()) { service.Remove(string.Format(RedisKey.AdminToken, token)); } return(Succeed()); }
/// <summary> /// 获取 /// </summary> /// <param name="token">认证信息</param> /// <returns></returns> public T_Sys_User Get(string token = null) { var _token = token ?? RequestAuthorize.GetRequestToken; if (_token != null) { using RedisStringService service = new RedisStringService(); return(service.Get <T_Sys_User>(_token)); } else { return(null); } }
/// <summary> /// 获得总线网关要添加的设备信息sendsocket(8, "8;876;"+zhujitype+";"+devmac);//按一下总线开关,缓存总线开关mac地址,点击总线网关,返回当前要添加的几键开关 /// </summary> /// <param name="msg">1.查询总线网关下的开关connect user:123_Server type:other msg:123_e0ddc0a405d9;8;876;Safe_Center;58.57.32.162$/r$ /// 2.返回结果 123_e0ddc0a405d9;876;all;Zip;H4sIAAAAAAAEAGWQyw6CMBRE/6VrQ3gENLI38RuMi5tykRv6SlswxPjvoryqLufMTDvt5cHOFTuqTogdq7AnjrRq3pACBRJXIMC5msKCH8xoszhjU98EngQ+WvkhyvdRlkZJkZanpIyLKWq09evBwBtscQjKRjvypFWAeANKoVgISbgFazuHdlNG33sQHQZ158H/6eQXpAsAznWn1omfx8xrLY7B933fxNP2VVJXVNMQhmYUpioU6FGCbSfyvL4AcWAUMpEBAAA=$/r$ /// </param> public static string Host876(string msg) { try { if (msg.Split(';').Length >= 4) { using (RedisStringService service = new RedisStringService()) { string appUser = msg.Split(';')[0]; string account = appUser.Split('_')[0]; string devmac = msg.Split(';')[4].Replace("$/r$", ""); //本地外网ip string BusSwitchMac = service.Get("BusSwitch_" + devmac); //先提前按一下,瑞瀛网关服务器缓存开关mac地址,两分钟 if (!string.IsNullOrEmpty(BusSwitchMac)) { BusSwitchMac = BusSwitchMac.Replace("\"", ""); string[] macs = BusSwitchMac.Split(';'); List <host_device> deviceList = new List <host_device>(); foreach (var item in macs) { host_device host_Device = new host_device()//可能是个数组,有多个开关同时按的情况 { devmac = devmac + ";F1;" + BusSwitchMac, devtype = "03", devport = "0" }; deviceList.Add(host_Device); } string zipStr = EncryptionHelp.Encryption(JsonConvert.SerializeObject(deviceList), true); string msgResult = $"{appUser};876;all;Zip;{zipStr}$/r$";//拼接 log.Debug($"876 OK,返回设备类型的设备列表成功!返回信息:{msgResult}"); return(msgResult); } return(null); } } else { log.Debug($"855 Fail,命令不符合规范!"); return(null); } } catch (Exception) { throw; } }
public IActionResult Get() { this._logger.LogWarning($"服务启动成功"); string res = ""; using (RedisStringService service = new RedisStringService()) { res = service.Get("test1"); if (res == null) { for (int i = 0; i < 10000; i++) { res += "梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀梦的翅膀"; } service.Set <string>("test1", res); } } return(Ok($"当前ip:{_iConfiguration["ip"]},端口:{_iConfiguration["port"]},res:{res}"));//HttpStatusCode--200 }
private static bool IsGoOn = true;//秒杀活动是否结束 public static void Show() { using (RedisStringService service = new RedisStringService()) { service.Set <int>("Stock", 10);//是库存 } for (int i = 0; i < 5000; i++) { int k = i; Task.Run(() =>//每个线程就是一个用户请求 { using (RedisStringService service = new RedisStringService()) { if (IsGoOn) { long index = service.Decr("Stock");//-1并且返回 if (index >= 0) { Console.WriteLine($"{k.ToString("000")}秒杀成功,秒杀商品索引为{index}"); //service.Incr("Stock");//+1 //可以分队列,去数据库操作 } else { if (IsGoOn) { IsGoOn = false; } Console.WriteLine($"{k.ToString("000")}秒杀失败,秒杀商品索引为{index}"); } } else { Console.WriteLine($"{k.ToString("000")}秒杀停止......"); } } }); } Console.Read(); }
// unit对话接口 public static string unit_utterance() { string token = "";//#####调用鉴权接口获取的token##### using (RedisStringService service = new RedisStringService()) { token = service.Get("unit_token"); if (!string.IsNullOrEmpty(token)) { token = token.Replace("\"", ""); } else { string tokenJson = AccessToken.getAccessToken(); var tokenEntity = JsonConvert.DeserializeObject <UnitToken>(tokenJson); token = tokenEntity.access_token; service.Set("unit_token", tokenEntity.access_token, DateTime.Now.AddDays(29));//缓存29天 } } string host = "https://aip.baidubce.com/rpc/2.0/unit/service/chat?access_token=" + token; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host); request.Method = "post"; request.ContentType = "application/json"; request.KeepAlive = true; string str = "{\"log_id\":\"UNITTEST_10000\",\"version\":\"2.0\",\"service_id\":\"S15567\",\"session_id\":\"\",\"request\":{\"query\":\"你好\",\"user_id\":\"88888\"},\"dialog_state\":{\"contexts\":{\"SYS_REMEMBERED_SKILLS\":[\"1057\"]}}}"; // json格式 byte[] buffer = Encoding.UTF8.GetBytes(str); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string resultJson = reader.ReadToEnd(); dynamic resultEntity = JsonConvert.DeserializeObject <dynamic>(resultJson); string result = resultEntity.result.response_list[0].action_list[0].say.Value; Console.WriteLine("对话接口返回:"); Console.WriteLine(result); return(result); }
private static bool IsGoOn = true; //Continuing seckilling public static void Show() { using (RedisStringService service = new RedisStringService()) { service.Set <int>("Stock", 10); //Set 10 items in store } for (int i = 0; i < 100; i++) //Provide 100 client take part in the second kill { int k = i; Task.Run(() => { using (RedisStringService service = new RedisStringService()) { if (IsGoOn) { long index = service.Decr("Stock"); if (index >= 0) { Console.WriteLine($"{k.ToString("000")} seckilling succeed, index of item is {index}"); } else { if (IsGoOn) { IsGoOn = false; Console.WriteLine($"{k.ToString("000")} seckilling failed, index of item is {index}"); } } } else { Console.WriteLine($"{k.ToString("000")} , seckilling is over, sorry."); } } } ); } }
public override void OnAuthorization(HttpActionContext actionContext) { if (IsAllowAnonymous(actionContext)) { return; } var token = GetToken(actionContext); if (string.IsNullOrWhiteSpace(token)) { HandleUnauthenticatedRequest(actionContext, "Token为空。"); } using (var service = new RedisStringService()) { var userInfo = service.Get <UserInfo>(string.Format(RedisKey.AdminToken, token)); if (userInfo == null) { HandleUnauthenticatedRequest(actionContext, "token无效。"); } base.OnAuthorization(actionContext); } }
public IHttpActionResult Login(LoginRequest request) { var user = _sysUserService.FirstOrDefault(a => a.UserName == request.UserName && a.Disable == (short)BaseModel.DisableEnum.Normal); if (user == null) { return(Fail("用户不存在")); } if (user.Password != request.Password) { return(Fail("密码错误!")); } var roles = _sysUserService.GetRoles(); var userInfo = new UserInfo { UserName = user.UserName, Name = user.Name, Avatar = user.Avatar, Id = user.Id, IsManager = user.IsManager, Mobile = user.Mobile, Roles = new int[] { 1, 2, 3, 4 }, Expired = DateTime.Now }; using (var service = new RedisStringService()) { var token = MD5Encrypt.Encrypt($"{DateTime.Now.ToString("MMdd")}{userInfo.UserName}{DateTime.Now}{Util.MicroTime()}"); service.Set(string.Format(RedisKey.AdminToken, token), userInfo); return(Succeed(new LoginResponse { UserName = user.UserName, Token = token, Id = user.Id, })); } }
public static void Show() { UserInfo user = new UserInfo() { Id = 123, Account = "Administrator", Address = "武汉市", Email = "*****@*****.**", Name = "Eleven", Password = "******", QQ = 57265177 }; using (RedisStringService service = new RedisStringService()) { //service.Set<string>($"userinfo_{user.Id}", Newtonsoft.Json.JsonConvert.SerializeObject(user)); service.Set <UserInfo>($"userinfo_{user.Id}", user); var userCacheList = service.Get <UserInfo>(new List <string>() { $"userinfo_{user.Id}" }); var userCache = userCacheList.FirstOrDefault(); //string sResult = service.Get($"userinfo_{user.Id}"); //var userCache = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfo>(sResult); userCache.Account = "Admin"; service.Set <UserInfo>($"userinfo_{user.Id}", userCache); } using (RedisHashService service = new RedisHashService()) { service.FlushAll(); //反射遍历做一下 service.SetEntryInHash($"userinfo_{user.Id}", "Account", user.Account); service.SetEntryInHash($"userinfo_{user.Id}", "Name", user.Name); service.SetEntryInHash($"userinfo_{user.Id}", "Address", user.Address); service.SetEntryInHash($"userinfo_{user.Id}", "Email", user.Email); service.SetEntryInHash($"userinfo_{user.Id}", "Password", user.Password); service.SetEntryInHash($"userinfo_{user.Id}", "Account", "Admin"); service.StoreAsHash <UserInfo>(user);//含ID才可以的 var result = service.GetFromHash <UserInfo>(user.Id); } UserInfo user2 = new UserInfo() { Id = 234, Account = "Administrator2", Address = "武汉市2", Email = "[email protected]", Name = "Eleven2", Password = "******", QQ = 572651772 }; using (RedisHashService service = new RedisHashService()) { service.FlushAll(); //反射遍历做一下 service.SetEntryInHash($"userinfo_{user2.Id}", "Account", user2.Account); service.SetEntryInHash($"userinfo_{user2.Id}", "Name", user2.Name); service.SetEntryInHash($"userinfo_{user2.Id}", "Address", user2.Address); service.SetEntryInHash($"userinfo_{user2.Id}", "Email", user2.Email); service.SetEntryInHash($"userinfo_{user2.Id}", "Remark", "这里是2号用户"); service.StoreAsHash <UserInfo>(user);//含ID才可以的 var result = service.GetFromHash <UserInfo>(user.Id); } }
/// <summary> /// 服务器端不停的接收客户端发来的消息 /// </summary> /// <param name="o"></param> public void Received(object o) { try { Socket socketSend = o as Socket; string ip = ((IPEndPoint)socketSend.RemoteEndPoint).Address.ToString(); while (true) { //客户端连接服务器成功后,服务器接收客户端发送的消息 byte[] buffer = new byte[1024 * 1024 * 2];// //实际接收到的有效字节数 int len = socketSend.Receive(buffer); if (len == 0) { break; } //204为ccdd开头的cc //99为从汉字转换到16进制ToHex》16进制字节strToToHexByte》 //《字节转16进制X2,《16进制字符串转字符串UnHex if (buffer[0] == 204 || buffer[0] == 99 || buffer[0] == 227 || buffer[0] == 236) { string strData = string.Empty; for (int i = 0; i < len; i++) { strData += buffer[i].ToString("X2") + " "; //十六进制 } log.Debug(socketSend.RemoteEndPoint + "收到消息<<<<<<<<<:" + strData); //Console.WriteLine(socketSend.RemoteEndPoint + "收到消息<<<<<<<<<:" + strData); //string dd = buffer[0].ToString(); //log.Debug($"字节1为:{dd}, 转字符串长度:{strData.Length}"); if (strData.Length == 33 && strData.Substring(12, 2) == "05") { using (RedisHashService service = new RedisHashService()) { //命令开关 //CC DD F1 06 05 00 08 01 01 8D EF //cc dd 开头固定 //f1 第一个485通道 //06 物理地址 //05 00 08 //00 继电器 //01 为打开继电器 //8D C8 为crc校验码 bool st = strData.Substring(24, 2) == "01" ? true : false; string ff = strData.Substring(6, 2); string mac = strData.Substring(9, 2); string port = strData.Substring(21, 2); int iport = int.Parse(port) + 1; string key = ip + ";" + ff + ";" + mac + "_0;" + iport; //58.57.32.162;F1;06_0;3 service.SetEntryInHash("DeviceStatus", key, st.ToString()); //解决默认posid都为0的问题 log.Debug($"状态改变:{key}:{st.ToString()}"); } } else if (strData.Length == 39 && strData.Substring(12, 2) == "20") { //39:手动操作开关为一组, //cc dd f1 06 20 10 11 00 01 00 00 4e b0 cc dd f1 06 20 10 11 00 01 00 7f 0f 50 //cc dd f1 01 20 10 13 00 01 00 00 76 96 cc dd f1 01 20 10 13 00 01 00 7f 37 76 using (RedisStringService service = new RedisStringService()) { Gateway_SessionDic.AddOrUpdate(ip, socketSend, (Func <string, Socket, Socket>)((key, oldValue) => socketSend)); service.Set("BusSwitch_" + ip, strData.Substring(9, 2), new TimeSpan(0, 0, 0, 120));//缓存2分钟 log.Debug($"缓存mac:BusSwitch_{ip}:{strData.Substring(9, 2)}"); //第七位为继电器编号左侧1,11(比指令00+11),第11位为状态(ff开,f7关) //第一个开 //cc dd f1 05 20 10 11 00 01 00 80 0f 05 //cc dd f1 05 20 10 11 00 01 00 ff 4e e5 //中间关 //cc dd f1 05 20 10 12 00 01 00 00 4a a5 //cc dd f1 05 20 10 12 00 01 00 7f 0b 45 } } else if (strData.Length == 24) { //修改mac地址CC DD F1 01 06 00 02 01 03 69 9B //第一种24 //cc dd f1 01 06 00 (01->02) //cc dd f1 02 02 01 e8 aa (第二行的第四位02) //CC DD F1 02 06 00 (02->04) //CC DD F1 02 04 01 EB 39 (第二行的第四位04) //cc dd f1 02 06 00 (02->03) //cc dd f1 02 03 01 e9 09 //cc dd f1 03 06 00 (03->02) //cc dd f1 02 02 01 e9 48 //cc dd f1 02 06 00 (02->01) //cc dd f1 02 01 01 e8 69 using (RedisStringService service = new RedisStringService()) { Gateway_SessionDic.AddOrUpdate(ip, socketSend, (Func <string, Socket, Socket>)((key, oldValue) => socketSend)); service.Set("BusSwitch_" + ip, strData.Substring(12, 2), new TimeSpan(0, 0, 0, 120));//缓存2分钟 log.Debug($"BusSwitch_{ip} 修改为新的mac: {strData.Substring(12, 2)}"); } } else if (strData.Length == 21) { //修改mac地址成功 //CC DD F1 01 06 00 02 01 03 69 9B //cc dd f1 01 06 00 02 01 01 e8 5a //CC DD F1 01 06 00 02 01 01 E8 5A //第二种* 21 //CC DD F1 02 06 00 02 (02->01) //CC DD F1 01 01 E8 69 //CC DD F1 04 06 00 02 //CC DD F1 05 01 EA CF //cc dd F1 03 06 00 02 01 04 29 bb(03->04) //CC DD F1 03 06 00 02 //CC DD F1 04 01 EA E8 //第三种33 //cc dd f1 01 06 00 02 02 01 e8 aa (未处于配置状态) using (RedisStringService service = new RedisStringService()) { Gateway_SessionDic.AddOrUpdate(ip, socketSend, (Func <string, Socket, Socket>)((key, oldValue) => socketSend)); service.Set("BusSwitch_" + ip, strData.Substring(9, 2), new TimeSpan(0, 0, 0, 120));//缓存2分钟 log.Debug($"BusSwitch_{ip} 修改为新的mac: {strData.Substring(9, 2)}"); } } else if (strData.Contains("7C") && strData.Contains("3B"))//|; { //35 38 2E 35 37 2E 33 32 2E 31 36 32 3B 46 31 3B 30 35 7C 63 63 20 64 64 20 30 31 20 30 36 20 30 30 20 30 32 20 30 31 20 30 35 20 65 39 20 39 39 //63 63 20 64 64 20 //cc dd f1 06 05 00 08 00 01 8c 7f|192.168.82.107;f1;06 //cc dd f1 01 06 00 02 01 05 e9 99|58.57.32.162;F1;05 //cc dd f1 01 06 00 02 01 05 e9 99|192.168.82.107;f1;06 string strDataStr = UnHex(strData, "utf-8"); log.Debug($"收到请求: {strDataStr}"); string ipmac = strDataStr.Split('|')[1].ToString(); string wwip = ipmac.Split(';')[0].ToString(); string msg = strDataStr.Split('|')[0].ToString(); //1.开关开关指令,需要三个参数,开关物理地址+继电器地址+开关值+crc校验 //01 05 00 08 00 01 8D C8 //第一位 01 为开关物理地址 //第五位 00(00为第一个继电器,01为第二个继电器,02为第三个继电器) //第六位 01 为打开继电器,00为关闭继电器 //第七八位 为crc校验码,百度查找c# 的crc校验函数 //2.发送配置物理地址指令 //01 06 00 02 01 03 69 9B //第六位 03 为开关新的物理地址,第七八位 为crc校验码 //新的固件第一位01固定,老的固件第一位为原mac地址 if (Gateway_SessionDic.ContainsKey(wwip)) { byte[] bytes = strToToHexByte(msg); Gateway_SessionDic[wwip].Send(bytes); log.Debug($"给控制器{wwip}发送指令:{msg}"); } else { log.Debug($"请求网关的session不存在 {ipmac}: {msg}"); } } else if (strData.Length == 66) { string mac = strData.Substring(6, 2); string fl = strData.Substring(15, 2); byte[] bytes = strToToHexByte(strData); //Gateway_SessionDic[fl].Send(bytes); log.Debug($"给控制器{fl}发送指令:{strData}"); //if (Gateway_SessionDic.ContainsKey(fl)) //{ // byte[] bytes = strToToHexByte(strData); // Gateway_SessionDic[fl].Send(bytes); // log.Debug($"给控制器{fl}发送指令:{strData}"); //} //else //{ // log.Debug($"请求网关的session不存在 {fl}: {strData}"); //} using (RedisHashService service = new RedisHashService()) { service.SetEntryInHash("DeviceStatus", mac, "_" + fl); log.Debug($"状态电梯改变:{mac}:{fl}"); } } else if (strData.Length == 15) { //确认梯控应答 //EC 88 08 01 0D string mac = strData.Substring(6, 2); using (RedisHashService service = new RedisHashService()) { string _fl = service.GetValueFromHash("DeviceStatus", mac); string fl = _fl.Replace("_", ""); service.SetEntryInHash("DeviceStatus", mac, fl); log.Debug($"状态电梯改变:{mac}:{fl}"); } } } } } catch { } }
public static void Show() { Student student_1 = new Student() { Id = 11, Name = "Eleven" }; Student student_2 = new Student() { Id = 12, Name = "Twelve", Remark = "123423245" }; Console.WriteLine("*****************************************"); { //key value 都是string 假如是个对象呢?序列化一下 //假如要修改某一个属性的值 读--反序列化--修改--序列化 memcached using (RedisStringService service = new RedisStringService()) { service.KeyFulsh(); service.StringSet("RedisStringService_key1", "RedisStringService_value1"); Console.WriteLine(service.StringGet("RedisStringService_key1")); Console.WriteLine(service.StringGetSet("RedisStringService_key1", "RedisStringService_value2")); Console.WriteLine(service.StringGet("RedisStringService_key1")); service.StringAppend("RedisStringService_key1", "Append"); Console.WriteLine(service.StringGet("RedisStringService_key1")); service.StringSet("RedisStringService_key1", "RedisStringService_value", new TimeSpan(0, 0, 0, 5)); Console.WriteLine(service.StringGet("RedisStringService_key1")); Thread.Sleep(5000); Console.WriteLine(service.StringGet("RedisStringService_key1")); } } //保存 查询对象: //Student_2_id 12 Student_2_Name Twelve // 序列化后保存一个对象没问题, //查询--反序列化--修改--序列化--保存 Console.WriteLine("*****************************************"); { using (RedisHashService service = new RedisHashService()) { //service.KeyFulsh(); //service.SetEntryInHash("lisi", "id", "15"); //service.SetEntryInHash("zhangsan", "id", "13"); //service.SetEntryInHash("zhangsan", "Name", "Thirteen"); //service.SetEntryInHashIfNotExists("zhangsan", "Remark", "1234567"); //var value13 = service.GetHashValues("zhangsan"); //var key13 = service.GetHashKeys("zhangsan"); //var dicList = service.GetAllEntriesFromHash("zhangsan"); //service.SetEntryInHash("zhangsan", "id", "14");//同一条数据,覆盖 //service.SetEntryInHash("zhangsan", "Name", "Fourteen"); //service.SetEntryInHashIfNotExists("zhangsan", "Remark", "2345678");//同一条数据,不覆盖 //service.SetEntryInHashIfNotExists("zhangsan", "Other", "234543");//没有数据就添加 //service.SetEntryInHashIfNotExists("zhangsan", "OtherField", "1235665"); //var value14 = service.GetHashValues("zhangsan"); //service.RemoveEntryFromHash("zhangsan", "Remark"); //service.SetEntryInHashIfNotExists("zhangsan", "Remark", "2345678"); //value14 = service.GetHashValues("zhangsan"); //service.StoreAsHash<Student>(student_1); //Student student1 = service.GetFromHash<Student>(11); //service.StoreAsHash<Student>(student_2); //Student student2 = service.GetFromHash<Student>(12); } } Console.WriteLine("*****************************************"); { //using (RedisSetService service = new RedisSetService()) //{ // //key--values // service.KeyFulsh(); // service.Add("Advanced", "111"); // service.Add("Advanced", "112"); // service.Add("Advanced", "113"); // service.Add("Advanced", "115"); // service.Add("Advanced", "114"); // service.Add("Advanced", "111"); // service.Add("Begin", "111"); // service.Add("Begin", "112"); // service.Add("Begin", "113"); // service.Add("Begin", "117"); // service.Add("Begin", "116"); // service.Add("Begin", "111"); // service.Add("Internal", "111"); // service.Add("Internal", "112"); // service.Add("Internal", "117"); // service.Add("Internal", "119"); // service.Add("Internal", "118"); // service.Add("Internal", "111"); // var result = service.GetAllItemsFromSet("Advanced"); // var result2 = service.GetRandomItemFromSet("Advanced"); // result = service.GetAllItemsFromSet("Begin"); // result2 = service.GetRandomItemFromSet("Begin"); // var result3 = service.GetIntersectFromSets("Advanced", "Begin");//交 // result3 = service.GetDifferencesFromSet("Advanced", "Begin", "Internal");//差 // result3 = service.GetUnionFromSets("Advanced", "Begin", "Internal");//并 // service.RemoveItemFromSet("Advanced", "111"); // result = service.GetAllItemsFromSet("Advanced"); // service.RandomRemoveItemFromSet("Advanced"); // result = service.GetAllItemsFromSet("Advanced"); //} } Console.WriteLine("*****************************************"); { //using (RedisZSetService service = new RedisZSetService()) //{ // service.KeyFulsh(); // service.Add("score", "111"); // service.Add("score", "112"); // service.Add("score", "113"); // service.Add("score", "114"); // service.Add("score", "115"); // service.Add("score", "111"); // service.AddItemToSortedSet("user", "Eleven1", 1); // service.AddItemToSortedSet("user", "Eleven2", 2); // service.AddItemToSortedSet("user", "Eleven3", 5); // service.AddItemToSortedSet("user", "Eleven4", 3); // service.AddItemToSortedSet("user", "1Eleven2", 4); // var list = service.GetAll("score"); // var listDesc = service.GetAllDesc("score"); // var user = service.GetAll("user"); // var userDesc = service.GetAllDesc("user"); //} } Console.WriteLine("*****************************************"); { using (RedisListService service = new RedisListService()) { service.KeyFulsh(); List <string> stringList = new List <string>(); for (int i = 0; i < 10; i++) { stringList.Add(string.Format($"放入任务{i}")); } service.ListLeftPush("test", "这是一个学生1"); service.ListLeftPush("test", "这是一个学生2"); service.ListLeftPush("test", "这是一个学生3"); service.ListLeftPush("test", "这是一个学生4"); service.ListLeftPush("test", "这是一个学生5"); service.ListLeftPush("test", "这是一个学生6"); service.ListLeftPush("task", stringList); Console.WriteLine(service.ListLength("test")); Console.WriteLine(service.ListLength("task")); var list = service.ListRange <string>("test"); Action act = new Action(() => { while (true) { Console.WriteLine("************请输入数据**************"); string testTask = Console.ReadLine(); service.ListLeftPush("test", testTask); } }); act.EndInvoke(act.BeginInvoke(null, null)); } } }
public HomeController(ILogger<HomeController> logger, Microsoft.AspNetCore.Mvc.Infrastructure.IClientErrorFactory clientError, RedisStringService redisStringService, RedisHashService redisHashService) { _logger = logger; _redisStringService = redisStringService; _redisHashService = redisHashService; }
public static void Show() { Student student_1 = new Student() { Id = 11, Name = "Eleven" }; Student student_2 = new Student() { Id = 12, Name = "Twelve", Remark = "123423245" }; Console.WriteLine("====Basic redis test===="); { using (RedisStringService service = new RedisStringService()) { service.Set <string>("student1", "May"); Console.WriteLine(service.Get("student1")); service.Append("student1", " from china"); Console.WriteLine($"After append : {service.Get("student1")}"); service.GetAndSetValue("student1", "Modified May "); Console.WriteLine(service.Get("student1")); service.Set <string>("stu2", "Lee", DateTime.Now.AddSeconds(5)); //Thread.Sleep(1000); Console.WriteLine(service.Get("stu2")); service.Set <int>("age", 23); service.Incr("age"); Console.WriteLine($"After Incr: {service.Get("age")}"); service.IncrBy("age", 10); Console.WriteLine($"After Incr by 10: {service.Get("age")}"); service.Decr("age"); Console.WriteLine($"After Decr: {service.Get("age")}"); service.DecrBy("age", 10); Console.WriteLine($"After Decr by 10: {service.Get("age")}"); } { Console.WriteLine("===Basic redis hash table==="); using (RedisHashService service = new RedisHashService()) { service.SetEntryInHash("stuHash", "id", "123"); service.SetEntryInHash("stuHash", "name", "MayHash"); service.SetEntryInHash("stuHash", "remark", "Graudate"); var keys = service.GetHashKeys("stuHash"); var values = service.GetHashValues("stuHash"); var keyValues = service.GetAllEntriesFromHash("stuHash"); string valueId = service.GetValueFromHash("stuHash", "id"); Console.WriteLine(valueId); service.SetEntryInHashIfNotExists("stuHash", "name", "MayHashUpdated"); service.SetEntryInHashIfNotExists("stuHash", "description", "Advanced class"); Console.WriteLine(service.GetValueFromHash("stuHash", "name")); Console.WriteLine(service.GetValueFromHash("stuHash", "description")); service.RemoveEntryFromHash("stuHash", "description"); Console.WriteLine($"After remove: {service.GetValueFromHash("stuHash", "description")}"); } } } }