实例介绍
【实例简介】
其中包含了Redis并发锁、Redis事务、Redis中List<T>/Hash<T>的读取、计数器、Redis队列、RedisTypedClient等示例
因为示例调用的是本机的Redis,所以需确保您的windows下已经安装了Redis,具体安装方式见 http://www.haolizi.net/example/view_8572.html
或者 更改Redis连接的ip地址为你的Redis服务器地址也可以
【实例截图】





【核心代码】
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ServiceStack.Redis;
using ServiceStack.Redis.Generic;
namespace SSRedisDemo
{
public partial class Form1 : Form
{
public static IRedisClientsManager clientsManager=null;
public static IRedisClient redisClient=null;
public Form1()
{
InitializeComponent();
var count = this.tabControl1.TabCount;
for (int i = 0; i < count; i )
{
this.tabControl1.GetControl(i).Enabled = false;
}
this.tabControl1.GetControl(0).Enabled = true;
}
private void btnConn_Click(object sender, EventArgs e)
{
try
{
#region 集群访问方式
var host = String.Format("{2}@{0}:{1}", this.txtHost.Text, this.txtPort.Text, this.txtPwd.Text);
clientsManager = new PooledRedisClientManager(new string[] {host});
redisClient = clientsManager.GetClient();
#endregion
#region 单个实例方式
//redisClient = new RedisClient(this.txtHost.Text, Int32.Parse(this.txtPort.Text),this.txtPwd.Text);
#endregion
}
catch(Exception ex)
{
MessageBox.Show("失败:" ex.Message);
return;
}
MessageBox.Show("成功");
var count = this.tabControl1.TabCount;
for (int i = 0; i < count; i )
{
this.tabControl1.GetControl(i).Enabled = true;
}
}
private void btnSetString_Click(object sender, EventArgs e)
{
redisClient.Set(this.txtStringKey.Text, this.txtStringValue.Text);
}
private void btnGetString_Click(object sender, EventArgs e)
{
var strValue=redisClient.Get<string>(this.txtStringKey.Text);
MessageBox.Show(strValue);
}
private void btnTransaction_Click(object sender, EventArgs e)
{
using (IRedisClient RClient = clientsManager.GetClient())
{
RClient.Add("key", 1);
using (IRedisTransaction IRT = RClient.CreateTransaction())
{
IRT.QueueCommand(r => r.Set("key", 20));
IRT.QueueCommand(r => r.Increment("key", 1));
IRT.Commit(); // 提交事务
}
MessageBox.Show(RClient.Get<string>("key"));
}
}
private void btnAcquireLock_Click(object sender, EventArgs e)
{
using (IRedisClient RClient = clientsManager.GetClient())
{
RClient.Add("mykey", 1);
// 支持IRedisTypedClient和IRedisClient
using (RClient.AcquireLock("testlock"))
{
//Response.Write("申请并发锁<br/>");
var counter = RClient.Get<int>("mykey");
Thread.Sleep(100);
RClient.Set("mykey", counter 1);
MessageBox.Show(RClient.Get<int>("mykey").ToString());
}
}
}
private void btnQueue_Click(object sender, EventArgs e)
{
redisClient.EnqueueItemOnList("operLog", "操作时间:" DateTime.Now.ToString());
MessageBox.Show("写入成功");
}
private void btnQueueRead_Click(object sender, EventArgs e)
{
string msg = redisClient.DequeueItemFromList("operLog");
MessageBox.Show(msg);
}
/// <summary>
/// DecrementValue 根据指定的Key,将值减1(仅整型有效)
///DecrementValueBy 根据指定的Key,将值减去指定值(仅整型有效)
///IncrementValue 根据指定的Key,将值加1(仅整型有效)
///IncrementValueBy 根据指定的Key,将值加上指定值(仅整型有效)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnIncStart_Click(object sender, EventArgs e)
{
var key = "incKey";
var v = redisClient.IncrementValue(key);//将值加1(仅整型有效)
redisClient.IncrementValueBy(key, 100);//将值加100
MessageBox.Show("Success");
}
private void btnIncStop_Click(object sender, EventArgs e)
{
var key = "incKey";
var v = redisClient.Get<long>(key);
MessageBox.Show("当前值:" v.ToString());
}
private void btnTypedClient_Click(object sender, EventArgs e)
{
Person p1 = new Person() { Id = 1, Name = "刘备" };
Person p2 = new Person() { Id = 2, Name = "关羽" };
Person p3 = new Person() { Id = 3, Name = "张飞" };
Person p4 = new Person() { Id = 4, Name = "曹操" };
Person p5 = new Person() { Id = 5, Name = "典韦" };
Person p6 = new Person() { Id = 6, Name = "郭嘉" };
List<Person> ListPerson = new List<Person>() { p2, p3, p4, p5, p6 };
using (IRedisClient RClient = clientsManager.GetClient())
{
IRedisTypedClient<Person> IRPerson = RClient.As<Person>();
IRPerson.DeleteAll();
//------------------------------------------添加--------------------------------------------
//添加单条数据
IRPerson.Store(p1);
//添加多条数据
IRPerson.StoreAll(ListPerson);
//------------------------------------------查询--------------------------------------------
//Linq支持
MessageBox.Show("Id == 1 的Name:" IRPerson.GetAll().Where(m => m.Id == 1).First().Name); //刘备
//注意,用IRedisTypedClient的对象IRPerson的Srore()添加的才能用IRPerson()方法读取
MessageBox.Show("Id == 2 的Name:" IRPerson.GetAll().First(m => m.Id == 2).Name); //关羽
//------------------------------------------删除--------------------------------------------
IRPerson.Delete(p1); //删除 刘备
MessageBox.Show("删除刘备后总数:" IRPerson.GetAll().Count()); //5
IRPerson.DeleteById(2); //删除 关羽
MessageBox.Show("删除关羽后总数:" IRPerson.GetAll().Count()); //4
IRPerson.DeleteByIds(new List<int> { 3, 4 }); //删除张飞 曹操
MessageBox.Show("删除张飞曹操后总数:" IRPerson.GetAll().Count()); //2
IRPerson.DeleteAll(); //全部删除
MessageBox.Show("全部删除后总数:" IRPerson.GetAll().Count()); //0
}
}
private void btnTestAddSetReplace_Click(object sender, EventArgs e)
{
using (IRedisClient RClient = clientsManager.GetClient())
{
RClient.Add("c1", "缓存1");
RClient.Set("c1", "缓存2");
RClient.Replace("c1", "缓存3");
MessageBox.Show(RClient.Get<string>("c1"));
RClient.Remove("c1");
MessageBox.Show("移除状态:" (RClient.Get<string>("c1") == null));
}
}
private void btnList_T_Click(object sender, EventArgs e)
{
using (IRedisClient RClient = clientsManager.GetClient())
{
//内部维护一个List<T>集合
RClient.AddItemToList("蜀国", "刘备");
RClient.AddItemToList("蜀国", "关羽");
RClient.AddItemToList("蜀国", "张飞");
List<string> ListString = RClient.GetAllItemsFromList("蜀国");
foreach (string str in ListString)
{
MessageBox.Show(str); //输出 刘备 关羽 张飞
}
}
}
private void btnHash_T_Click(object sender, EventArgs e)
{
using (IRedisClient RClient = clientsManager.GetClient())
{
//Hash<T>
RClient.AddItemToSet("魏国", "曹操");
RClient.AddItemToSet("魏国", "曹操");
RClient.AddItemToSet("魏国", "典韦");
HashSet<string> HashSetString = RClient.GetAllItemsFromSet("魏国");
foreach (string str in HashSetString)
{
MessageBox.Show(str); //输出 典韦 曹操
}
}
}
private void btnList_Range_Click(object sender, EventArgs e)
{
using (IRedisClient RClient = clientsManager.GetClient())
{
//内部维护一个List<T>集合
RClient.AddItemToSortedSet("蜀国1", "刘备", 5);
RClient.AddItemToSortedSet("蜀国1", "关羽", 2);
RClient.AddItemToSortedSet("蜀国1", "张飞", 3);
IDictionary<String, double> DicString = RClient.GetRangeWithScoresFromSortedSet("蜀国1", 0, 2);
foreach (var r in DicString)
{
MessageBox.Show(r.Key ":" r.Value); //输出 关羽 张飞 刘备
}
}
}
private void btnHashTable_Click(object sender, EventArgs e)
{
using (IRedisClient RClient = clientsManager.GetClient())
{
RClient.SetEntryInHash("xxx", "key", "123");
List<KeyValuePair<string, string>> keyValuePairs = new List<KeyValuePair<string, string>>();
KeyValuePair<string, string> kvp = new KeyValuePair<string, string>("key", "1");
keyValuePairs.Add(kvp);
RClient.SetRangeInHash("xxx", keyValuePairs);
MessageBox.Show(string.Join("\r\n", RClient.GetHashValues("xxx").ToArray()));
}
}
private void btnSaveT_Click(object sender, EventArgs e)
{
var keyT = "tkey";
redisClient.Set(keyT, new Person() { Id = 6, Name = "好例子" });
var p = redisClient.Get<Person>(keyT);
MessageBox.Show(p.Name);
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
}
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明


网友评论
我要评论