static void RedisNativeClientInterface() { using (IRedisNativeClient client = new RedisClient()) { client.Set("urn:messages:1", Encoding.UTF8.GetBytes("Hello C# World!")); } using (IRedisNativeClient client = new RedisClient()) { var result = Encoding.UTF8.GetString(client.Get("urn:messages:1")); Console.WriteLine("Message: {0}", result); var delkeys = client.Del("urn:messages:1"); Console.WriteLine("Key {0} deleted.", delkeys); } }
private static void DemoRedisNativeClient() { const string key = "urn:messages:1"; using (IRedisNativeClient redisNativeClient = new RedisClient()) { redisNativeClient.Set(key, Encoding.UTF8.GetBytes("Hello World")); } using (IRedisNativeClient redisNativeClient = new RedisClient()) { byte[] bytes = redisNativeClient.Get(key); string result = Encoding.UTF8.GetString(bytes); Console.WriteLine($"Message = {result}"); } }
/// <summary> /// ServiceStack.Redis(收费的) 实现秒杀, /// </summary> /// <param name="id"></param> /// <param name="minute"></param> public static void Seckill2(string id, int minute) { using (RedisClient redisClient = new RedisClient("127.0.0.1", 6379)) { //ServiceStack的例子,stock在存的时候要用int值,不然会报错 redisClient.Set <int>("stock", 10); } Console.WriteLine($"在{minute}分0秒开始抢购"); var start = true; while (start) { if (minute == DateTime.Now.Minute) { start = false; for (int i = 0; i < 10; i++) { string name = $"客户端{id}:{i}"; Task.Run(() => { using (RedisClient redisClient = new RedisClient("127.0.0.1", 6379)) { long result = redisClient.Decr("stock"); if (result >= 0) { Console.WriteLine($"{name}******************抢购成功**************"); } else { Console.WriteLine($"{name}抢购失败"); } } }); Thread.Sleep(10); } } } }
static void Main(string[] args) { using (IRedisNativeClient client = new RedisClient()) { client.Set("urn:messages:1", Encoding.UTF8.GetBytes("Hello C# World!")); } using (IRedisNativeClient client = new RedisClient()) { var result = Encoding.UTF8.GetString(client.Get("urn:messages:1")); Console.WriteLine("Message: {0}", result); } using (IRedisClient client = new RedisClient()) { var customerNames = client.Lists["urn:customernames"]; customerNames.Clear(); customerNames.Add("Joe"); customerNames.Add("Mary"); customerNames.Add("Bob"); } using (IRedisClient client = new RedisClient()) { var customerNames = client.Lists["urn:customernames"]; foreach (var customerName in customerNames) { Console.WriteLine("Customer: {0}", customerName); } } long lastId = 0; using (IRedisClient client = new RedisClient()) { var customerClient = client.GetTypedClient <Customer>(); var customer = new Customer() { Id = customerClient.GetNextSequence(), Address = "123 Main St", Name = "Bob Green", Orders = new List <Order> { new Order { OrderNumber = "AB123" }, new Order { OrderNumber = "AB124" } } }; var storedCustomer = customerClient.Store(customer); lastId = storedCustomer.Id; } using (IRedisClient client = new RedisClient()) { var customerClient = client.GetTypedClient <Customer>(); var customer = customerClient.GetById(lastId); Console.WriteLine("Got customer {0}, with name {1}", customer.Id, customer.Name); } using (IRedisClient client = new RedisClient()) { var transaction = client.CreateTransaction(); transaction.QueueCommand(c => c.Set("abc", 1)); transaction.QueueCommand(c => c.Increment("abc", 1)); transaction.Commit(); var result = client.Get <int>("abc"); Console.WriteLine(result); } using (IRedisClient client = new RedisClient()) { //client.PublishMessage("debug", "Hello C#!"); var sub = client.CreateSubscription(); sub.OnMessage = (c, m) => Console.WriteLine("Got message: {0}, from channel {1}", m, c); sub.SubscribeToChannels("news"); } Console.ReadLine(); }
public void SetCache(string key, object value) { redisClient.Set(key, value); }
static void Main(string[] args) { //1.0开启Redis的客户端,引入 using ServiceStack.Redis;命名空间 (连接服务器) using (RedisClient client = new RedisClient("127.0.0.1", 6379)) { //client.Password = "******"; //如果连接Redis的redis.windows.conf文件中的配置了访问密码,则在这设置将Password设为它的访问密码 //1.0---------------------------------- //将数据存储到了Redis服务器中 client.Set <string>("name", "zhangshang"); //获取数据 string name = client.Get <string>("name"); //删除key为蜀国的数据 client.Remove("蜀国"); //client.RemoveAllFromList("蜀国");或者移除key为蜀国的集合数据。 //2.0--------------------------------- //将数据存入到同一个key中,以list集合的方式存储。(看它如何在同一个key中添加不同的数据) client.AddItemToList("蜀国", "刘备"); client.AddItemToList("蜀国", "关羽"); client.AddItemToList("蜀国", "张飞"); client.AddItemToList("蜀国", "张飞"); //第一种获取数据的方式 (这里是获取key=“蜀国”的数据; 注意:这个key有两个值为“张飞”的数据) List <string> list = client.GetAllItemsFromList("蜀国"); list.ForEach(r => Console.WriteLine(r)); //输出:刘备 关羽 张飞 张飞 //第二种获取数据的方式 int listCount = (int)client.GetListCount("蜀国"); //获取key=“蜀国”的数据总条数 4 for (int i = 0; i < listCount; i++) { Console.WriteLine(client.GetItemFromList("蜀国", i)); } //3.0----------------------------------Set(消重) //用消重的方式,将数据存储到Redis服务器中 client.AddItemToSet("魏国", "曹操"); client.AddItemToSet("魏国", "曹操"); client.AddItemToSet("魏国", "曹植"); //获取数据 HashSet <string> ha = client.GetAllItemsFromSet("魏国"); //它返回的是一个HashSet的集合 List <string> list1 = ha.ToList(); //转成List list1.ForEach(r => Console.WriteLine(r)); //输出:曹操 曹植 (注意:因为我们写入了两个曹操,但是这里使用了Set去重,数以只输出了一个曹操) //4.0----------------------------------队列(队列的特点:先进先出) client.EnqueueItemOnList("吴国", "孙坚"); client.EnqueueItemOnList("吴国", "孙策"); client.EnqueueItemOnList("吴国", "周瑜"); int clistCount = (int)client.GetListCount("吴国"); //获取key=“吴国”的数据总条数 3 for (int i = 0; i < clistCount; i++) { //出队列(出了对列的数据项,都会被删除,所以如果一个数据项出了对列后,那么Redis里面就会被删除) Console.WriteLine(client.DequeueItemFromList("吴国")); } //为了测试出队列的数据项是否被删除,我们来做一个检测 if (client.GetAllItemsFromList("吴国").Any() == false) { Console.WriteLine("已经全部出队了,没有数据了"); } List <UserInfo> u = new List <UserInfo>() { new UserInfo() { Name = "1", Age = 1 }, new UserInfo() { Name = "2", Age = 11 }, new UserInfo() { Name = "3", Age = 12 }, }; //存储 client.Set <List <UserInfo> >("test", u); //获取 var q = client.Get <List <UserInfo> >("test"); foreach (var item in q) { Console.WriteLine(item.Name); } Console.ReadLine(); Console.ReadKey(); } }
/// <summary> /// 设置信息 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="token">key</param> /// <param name="obj">对象</param> public static void Set <T>(string token, T obj) where T : class, new() { client.Set <T>(token, obj); }
static void Main(string[] args) { var client = new RedisClient("m.xmbygy.com", 6380);//这两个参数的值要事先在配置文件Redis.conf里有配置的,两个参数分别为host、port //安装Redis服务后,最好不要让其在外网环境下面裸奔,可以为其设置一个复杂的访问密码,这样可以防止暴力破解 //配置文件中设置了访问密码,即加入了requirepass 123456789xdz,123456789xdz表示密码,则需要下面语句。 //client.Password = "******"; //Redis最基本功能——分布式缓存 client.Password = "******"; #region 常用数据类型:string client.Set <string>("key13", "xdz123"); //string name = client.Get<string>("name"); //Console.WriteLine(name); #endregion #region 常用数据类型:string //client.Add<string>("key11", "value11", DateTime.Now.AddMinutes(20));//为Redis缓存增加1条记录 //string s = client.Get<string>("key11"); //Console.WriteLine(s); #endregion #region 常用数据类型:set //client.AddItemToSet("HighSchool", "王斌"); //client.AddItemToSet("HighSchool", "曹浩华"); //client.AddItemToSet("HighSchool", "彭文将"); //HashSet<string> hashset1 = client.GetAllItemsFromSet("HighSchool"); //foreach (var item in hashset1) //{ // Console.WriteLine(item);//输出为值:王斌、曹浩华、彭文将 //} #endregion #region 序集合 sorted set //最后一个参数为我们排序的依据 //client.AddItemToSortedSet("12", "百度", 400);//第1个参数为key,第2个参数为value,第3个参数为排序依据,自己指定。加入到同一个集合,所以key都相同为12 //client.AddItemToSortedSet("12", "谷歌", 300); //client.AddItemToSortedSet("12", "阿里", 200); //client.AddItemToSortedSet("12", "新浪", 100); //client.AddItemToSortedSet("12", "人人", 500); ////升序获取第一个值: "新浪" //var list = client.GetRangeFromSortedSet("12", 0, 0);//第1个参数为key,第2个参数为从第几个,第3个参数为到第几个,表示从0个到0个,即表示第1个 ////var list = client.GetRangeFromSortedSet("12", 0, 2);//第1个参数为key,第2个参数为从第几个,第3个参数为到第几个,表示从0个到2个,即表示第1、2、3个,下面输出即为新浪、阿里、谷歌 //foreach (var item in list) //{ // Console.WriteLine(item); //} ////降序获取一个值: "人人" //list = client.GetRangeFromSortedSetDesc("12", 0, 0); //foreach (var item in list) //{ // Console.WriteLine(item); //} #endregion #region 数据结构:队列 //client.EnqueueItemOnList("LogQueue", "错误1……");//入队,键与下面同为LogQueue,说明进入的是同一个队列 //client.EnqueueItemOnList("LogQueue", "错误2……");//入队 ////============输出一条记录方法========== //string str1 = client.DequeueItemFromList("LogQueue");//出队 //Console.WriteLine(str1);//先进先出,所以输出为:错误1 // //============输出全部记录方法========== //long length = client.GetListCount("LogQueue"); //for (int i = 0; i < length; i++) //{ // Console.WriteLine(client.DequeueItemFromList("LogQueue")); //} #endregion #region 数据结构:栈 //client.PushItemToList("jinzhan", "入栈值1"); //client.PushItemToList("jinzhan", "入栈值2"); ////============输出一条记录方法========== //string str2 = client.PopItemFromList("jinzhan"); //Console.WriteLine(str2);//先进后出,后进先出,所以这里输出为:入栈值2 ////============输出全部记录方法========== //long length1 = client.GetListCount("jinzhan"); //for (int i = 0; i < length1; i++) //{ // Console.WriteLine(client.PopItemFromList("jinzhan")); //} #endregion string name = client.Get <string>("key13"); Console.WriteLine(name); Console.ReadKey(); }
static void Main(string[] args) { var loggerDebugFactory = new LoggerFactory(); loggerDebugFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true }); loggerDebugFactory.ConfigureNLog("nlog.config"); ILogger <Program> _logger = loggerDebugFactory.CreateLogger <Program>(); _logger.LogDebug(20, "Doing hard work! {Action}", "abc"); var a = 10; var b = 0; try { a = a / b; } catch (Exception ex) { _logger.LogError(ex, "this is a test"); } var messagesReceived = 0; using (var client = new RedisClient("localhost", 6379, "12345^")) { // redis type string. client.Set("student1", new Student { Id = 1, Name = "Nghiep", CreatedDate = DateTimeOffset.Now }); var student1 = client.Get <Student>("student1"); // redis type hash. client.StoreAsHash <Student>(new Student { Id = 4, Name = "Nghiep", CreatedDate = DateTimeOffset.Now }); var fromHash = client.GetFromHash <Student>(3); if (fromHash.Id != 0) { //Exited in cache } // redis type list. var redis = client.As <Student>(); var studentKey = string.Format("student:id:{0}", 1); var student = new Student { Id = 1, Name = "Nghiep", CreatedDate = DateTimeOffset.Now }; redis.SetValue(studentKey, student); studentKey = string.Format("student:id:{0}", 2); student = new Student { Id = 2, Name = "Nghiep", CreatedDate = DateTimeOffset.Now }; redis.SetValue(studentKey, student); var obj = redis.GetValues(new System.Collections.Generic.List <string> { "student:id:1", "student:id:2" }); using (var subscription = client.CreateSubscription()) { subscription.OnSubscribe = channel => { _logger.LogDebug(string.Format("Subscribed to '{0}'", channel)); }; subscription.OnUnSubscribe = channel => { _logger.LogDebug(string.Format("UnSubscribed from '{0}'", channel)); }; subscription.OnMessage = (channel, msg) => { _logger.LogDebug(string.Format("Received '{0}' from channel '{1}'", msg, channel)); //As soon as we've received all 5 messages, disconnect by unsubscribing to all channels if (++messagesReceived == PublishMessageCount) { subscription.UnSubscribeFromAllChannels(); } }; ThreadPool.QueueUserWorkItem(x => { Thread.Sleep(200); _logger.LogDebug("Begin publishing messages..."); using (var redisPublisher = new RedisClient("localhost", 6379, "12345^")) { for (var i = 1; i <= PublishMessageCount; i++) { var message = MessagePrefix + i; _logger.LogDebug(string.Format("Publishing '{0}' to '{1}'", message, ChannelName)); redisPublisher.PublishMessage(ChannelName, message); Thread.Sleep(2000); } } }); _logger.LogDebug(string.Format("Started Listening On '{0}'", ChannelName)); subscription.SubscribeToChannels(ChannelName); //blocking } } Console.ReadLine(); }