在.NET中使用Redis

时间:2022-12-17 06:13:46
dll文件

namespace RedisDemo
{
public partial class RedisPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ } protected void btn_Click(object sender, EventArgs e)
{
RedisClient redis = new RedisClient("127.0.0.1",6379);
//将字符串添加到Redis
List<string> storeMembers = new List<string>() {"one","two","three"};
storeMembers.ForEach(x=>redis.AddItemToList("additemtolist",x));
//得到指定key的values集合
Response.Write(redis.GetAllItemsFromList("additemtolist").Aggregate((current,a) => { return current += a + ","; }));
//根据索引位置数据
Response.Write("**********\n");
var item = redis.GetItemFromList("additemtolist",1);
Response.Write(item);
} protected void btn2_Click(object sender, EventArgs e)
{
RedisClient redis = new RedisClient("127.0.0.1", 6379);
var list = redis.Lists["additemtolist"];
list.Clear();//清空
//list.Remove("");//移除指定键值
//list.RemoveAt(1);//指定索引
} protected void btn3_Click(object sender, EventArgs e)
{
RedisClient redis = new RedisClient("127.0.0.1",6379);
//redis.Set<UserInfo>("userinfo",new UserInfo() { UserName="张三",Age = 45});
//UserInfo userinfo = redis.Get<UserInfo>("userinfo");
//Response.Write(userinfo.UserName);
var ser = new ObjectSerializer();
bool result = redis.Set<byte[]>("userinfo2",ser.Serialize(new UserInfo() {UserName="张二", Age=12}));
UserInfo usinfo2 = ser.Deserialize(redis.Get<byte[]>("userinfo2")) as UserInfo;
Response.Write(usinfo2.UserName);
} protected void btn4_Click(object sender, EventArgs e)
{
List<UserInfo> list = new List<UserInfo>()
{
new UserInfo{UserName="zzh",Age=14},
new UserInfo{UserName="aaa",Age=18}
};
var ser = new ObjectSerializer();
RedisClient redis = new RedisClient("127.0.0.1",6379);
redis.Set<byte[]>("list",ser.Serialize(list));
List<UserInfo> userinfoList = ser.Deserialize(redis.Get<byte[]>("list")) as List<UserInfo>;
userinfoList.ForEach(i=> {
literal.Text += "<p>"+i.UserName+"</p>";
});
}
}
[Serializable]
public class UserInfo
{
public int Id { get; set; }
public string UserName { get; set; }
public int Age { get; set; }
}
}