using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RedisStudyModel; using StackExchange.Redis; namespace RedisStuy { /// /// Redis Hash 学习 /// public class RedisHashStudy { private string studentHashKey = "student:hask:"; private IDatabase redisDatabase = RedisHelper.GetRedisDatabase(); /// /// 添加一个学生 /// public bool AddStudent(Student student) { try { HashEntry[] hashEntries = new HashEntry[] { new HashEntry("Id",student.Id), new HashEntry("Name",student.Name), new HashEntry("Age",student.Age), }; redisDatabase.HashSet(studentHashKey + student.Id, hashEntries, CommandFlags.None); return true; } catch { return false; } } /// /// 添加多个学生 /// public bool AddStudents(List students) { try { foreach (var student in students) { AddStudent(student); } return true; } catch { return false; } } /// /// 删除一个学生 /// public bool DelStudentById(int studentId) { return redisDatabase.KeyDelete(studentHashKey + studentId); } /// /// 查询一个学生 /// public Student QueryOneStudent(int studentId) { Student student = null; var studentHashEntryList = redisDatabase.HashGetAll(studentHashKey + studentId); if (studentHashEntryList.Length > 0) { student = new Student(); foreach (var temp in studentHashEntryList) { switch (temp.Name) { case "Id": student.Id = (int)temp.Value; break; case "Name": student.Name = temp.Value.HasValue ? temp.Value.ToString() : string.Empty; break; case "Age": student.Age = (int)temp.Value; break; } } } return student; } /// /// 查询一个学生 /// public Student QueryOneStudent(string redisKey) { Student student = null; var studentHashEntryList = redisDatabase.HashGetAll(redisKey); if (studentHashEntryList.Length > 0) { student = new Student(); foreach (var temp in studentHashEntryList) { switch (temp.Name) { case "Id": student.Id = (int)temp.Value; break; case "Name": student.Name = temp.Value.HasValue ? temp.Value.ToString() : string.Empty; break; case "Age": student.Age = (int)temp.Value; break; } } } return student; } /// /// 查询 所有学生 /// /// public List QueryAllStudents() { List students = new List(); var studdentKeys = RedisHelper.GetDefaultRedisServer().Keys(1, studentHashKey + "*", 200); foreach (var key in studdentKeys) { students.Add(QueryOneStudent(key)); } return students; } /// /// 查询某项的值 /// public void GetValue(int studentId, string haskFiledName) { var redisValue = redisDatabase.HashGet(studentHashKey + studentId, haskFiledName); } /// /// 更新一列的值 /// public void UpdateHashFile(int studentId, string haskFiledName, RedisValue redisValue) { redisDatabase.HashSet(studentHashKey + studentId, haskFiledName, redisValue); } /// /// 学生是否存在 /// public bool ExistStudent(int studentId) { bool exists = redisDatabase.KeyExists(studentHashKey + studentId); return exists; } } }