標籤:blog http io ar os sp for java strong
四、寫入資料在C# Redis實戰(三)中我們已經配置好了web.config程式,並且能通過C#代碼來讀取和管理以上配置資訊。接下來,就可以進行Redis的資料寫入了。Redis中可以用Store和StoreAll分別儲存單條和多條資料,C#中具體代碼如下:
1、儲存多條資料
[csharp] view plaincopy
- protected void btnOpenDB_Click(object sender, EventArgs e)
- {
- //System.Diagnostics.Process.Start("D:\\redis\\redis-server.exe");
- //lblShow.Text = "Redis已經開啟!";
-
- 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
、儲存單條資料
[csharp] view plaincopy
- 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() + "人!";
- }
- }
- }
:
如需轉載,請註明出處,本系列博文樣本程式
C# Redis實戰(四)