4、寫入數據
接下來,就能夠進行Redis的數據寫入了。Redis中能夠用Store和StoreAll分別保存單條和多條數據,C#中具體代碼以下:
一、保存多條數據
- protected void btnOpenDB_Click(object sender, EventArgs e)
- {
-
-
-
- using (var redisClient = RedisManager.GetClient())
- {
- var user = redisClient.GetTypedClient<User>();
-
- 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" }
- };
-
- var userToStore = new List<User> { qiujialong, chenxingxing, luwei, zhourui };
- user.StoreAll(userToStore);
-
- lblShow.Text = "目前共有:" + user.GetAll().Count.ToString() + "人!";
- }
- }
2、保存單條數據
- protected void btnInsert_Click(object sender, EventArgs e)
- {
- if (!string.IsNullOrEmpty(txtName.Text) && !string.IsNullOrEmpty(txtPosition.Text))
- {
- using (var redisClient = RedisManager.GetClient())
- {
- var user = redisClient.GetTypedClient<User>();
-
- var newUser = new User
- {
- Id = user.GetNextSequence(),
- Name = txtName.Text,
- Job = new Job { Position = txtPosition.Text }
- };
- user.Store(newUser);
-
- if (user.GetAll().Count > 0)
- {
- var htmlStr = string.Empty;
- foreach (var u in user.GetAll())
- {
- htmlStr += "<li>ID=" + u.Id + " 姓名:" + u.Name + " 所在部門:" + u.Job.Position + "</li>";
- }
- lblPeople.Text = htmlStr;
- }
- lblShow.Text = "目前共有:" + user.GetAll().Count.ToString() + "人!";
- }
- }
- }
效果圖: