当前位置: 首页>>代码示例>>C#>>正文


C# RedisConnection.Publish方法代码示例

本文整理汇总了C#中BookSleeve.RedisConnection.Publish方法的典型用法代码示例。如果您正苦于以下问题:C# RedisConnection.Publish方法的具体用法?C# RedisConnection.Publish怎么用?C# RedisConnection.Publish使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在BookSleeve.RedisConnection的用法示例。


在下文中一共展示了RedisConnection.Publish方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: TestSubscriberNameOnRemote

        private void TestSubscriberNameOnRemote(bool setName)
        {
            string id = Config.CreateUniqueName();

            using (var pub = new RedisConnection(Config.RemoteHost, allowAdmin: true))
            using (var sub = new RedisSubscriberConnection(Config.RemoteHost))
            {
                List<string> errors = new List<string>();
                EventHandler<BookSleeve.ErrorEventArgs> errorHandler = (sender, args) =>
                {
                    lock (errors) errors.Add(args.Exception.Message);
                };
                pub.Error += errorHandler;
                sub.Error += errorHandler;

                if (setName)
                {
                    pub.Name = "pub_" + id;
                    sub.Name = "sub_" + id;
                }
                int count = 0;
                var subscribe = sub.Subscribe("foo"+id, (key,payload) => Interlocked.Increment(ref count));

                Task pOpen = pub.Open(), sOpen = sub.Open();
                pub.WaitAll(pOpen, sOpen, subscribe);

                Assert.AreEqual(0, Interlocked.CompareExchange(ref count, 0, 0), "init message count");
                pub.Wait(pub.Publish("foo" + id, "hello"));

                PubSub.AllowReasonableTimeToPublishAndProcess();
                var clients = setName ? pub.Wait(pub.Server.ListClients()) : null;
                Assert.AreEqual(1, Interlocked.CompareExchange(ref count, 0, 0), "got message");
                lock (errors)
                {
                    foreach (var error in errors)
                    {
                        Console.WriteLine(error);
                    }
                    Assert.AreEqual(0, errors.Count, "zero errors");
                }
                if (setName)
                {
                    Assert.AreEqual(1, clients.Count(x => x.Name == pub.Name), "pub has name");
                    Assert.AreEqual(1, clients.Count(x => x.Name == sub.Name), "sub has name");
                }
            }
        }
开发者ID:raycode,项目名称:booksleeve,代码行数:47,代码来源:Connection.cs

示例2: ProcessQueue

        private static void ProcessQueue(RedisConnection connection, string[] queues)
        {
            var stopWatch = new Stopwatch();
            var formatter = new ObjectFormatter(maxLineLength: 5120);

            Logger.Info("ProcessQueue started.");

            while (true)
            {
                var message = connection.Lists.BlockingRemoveFirst(0, queues, DefaultTimeout);

                if (message.Result == null)
                {
                    continue;
                }

                var command = ExecuteCommand.Deserialize(message.Result.Item2);

                var timeInQueue = DateTime.UtcNow - command.Submitted;

                Logger.Info("Job received after {0:N3} seconds in queue.", timeInQueue.TotalSeconds);

                if (timeInQueue > command.TimeoutPeriod)
                {
                    Logger.Warn("Job was in queue for longer than {0} seconds, skipping!", command.TimeoutPeriod.Seconds);
                    continue;
                }

                stopWatch.Start();

                var result = Executer.Execute(command.Code, command.Classes);

                stopWatch.Stop();

                Logger.Info("Work completed in {0} milliseconds.", stopWatch.ElapsedMilliseconds);

                try
                {
                    var response = JsonConvert.SerializeObject(new
                                   {
                                       code = command.Code,
                                       classes = command.Classes,
                                       result = formatter.FormatObject(result),
                                       time = DateTime.UtcNow,
                                       duration = stopWatch.ElapsedMilliseconds
                                   });

                    var bytes = Encoding.UTF8.GetBytes(response);
                    var listeners = connection.Publish("workers:job-done:" + command.ClientId, bytes);

                    Logger.Info("Work results published to {0} listeners.", listeners.Result);
                }
                catch (JsonSerializationException ex)
                {
                    Logger.ErrorException("An error occurred while attempting to serialize the JSON result.", ex);
                }

                stopWatch.Reset();
            }
        }
开发者ID:spib,项目名称:Compilify,代码行数:60,代码来源:Program.cs

示例3: BroadcastReconnectMessage

        /// <summary>
        /// Prompt all clients to reconnect.
        /// </summary>
        public static void BroadcastReconnectMessage(RedisConnection connection)
        {
            if(connection == null) throw new ArgumentNullException("connection");

            connection.Wait(connection.Publish(RedisMasterChangedChannel, "*"));
        }
开发者ID:raycode,项目名称:booksleeve,代码行数:9,代码来源:ConnectionUtils.cs

示例4: SelectAndCreateConnection


//.........这里部分代码省略.........
                                            adminPreferred.Wait(adminPreferred.Server.MakeMaster());
                                        }
                                    }
                                }
                                else
                                {
                                    log.WriteLine("Slave should be promoted to master (but not done yet)...");
                                }
                            }
                            break;
                        case 1:
                            log.WriteLine("One master found; selecting");
                            preferred = masters[0];
                            break;
                        default:
                            log.WriteLine("Considering {0} masters...", masters.Count);
                            preferred = SelectWithTieBreak(log, masters, breakerScores);
                            break;
                    }

                }
                else
                { // we have been instructed to change master server
                    preferred = masters.Concat(slaves).FirstOrDefault(conn => (conn.Host + ":" + conn.Port) == newMaster);
                    if (preferred == null)
                    {
                        log.WriteLine("Selected new master not available: {0}", newMaster);
                    }
                    else
                    {
                        int errorCount = 0;
                        try
                        {
                            log.WriteLine("Promoting to master: {0}:{1}...", preferred.Host, preferred.Port);
                            preferred.Wait(preferred.Server.MakeMaster());
                            preferred.Strings.Set(0, TieBreakerKey, newMaster);
                            preferred.Wait(preferred.Publish(RedisMasterChangedChannel, newMaster));
                        }
                        catch (Exception ex)
                        {
                            log.WriteLine("\t{0}", ex.Message);
                            errorCount++;
                        }

                        if (errorCount == 0) // only make slaves if the master was happy
                        {
                            foreach (var conn in masters.Concat(slaves))
                            {
                                if (conn == preferred) continue; // can't make self a slave!

                                try
                                {
                                    log.WriteLine("Enslaving: {0}:{1}...", conn.Host, conn.Port);
                                    // set the tie-breaker **first** in case of problems
                                    conn.Strings.Set(0, TieBreakerKey, newMaster);
                                    // and broadcast to anyone who thinks this is the master
                                    conn.Publish(RedisMasterChangedChannel, newMaster);
                                    // now make it a slave
                                    conn.Wait(conn.Server.MakeSlave(preferred.Host, preferred.Port));
                                }
                                catch (Exception ex)
                                {
                                    log.WriteLine("\t{0}",ex.Message);
                                    errorCount++;
                                }
                            }
                        }
                        if (errorCount != 0)
                        {
                            log.WriteLine("Things didn't go smoothly; CHECK WHAT HAPPENED!");
                        }

                        // want the connection disposed etc
                        preferred = null;
                    }
                }

                if (preferred == null)
                {
                    selectedConfiguration = null;
                }
                else
                {
                    selectedConfiguration = preferred.Host + ":" + preferred.Port;
                    log.WriteLine("Selected server {0}", selectedConfiguration);
                }

                availableEndpoints = (from conn in masters.Concat(slaves)
                                      select conn.Host + ":" + conn.Port).ToArray();
                return preferred;
            }
            finally
            {
                foreach (var conn in connections)
                {
                    if (conn != null && conn != preferred) try { conn.Dispose(); }
                        catch { }
                }
            }
        }
开发者ID:IgorCandido,项目名称:NodeTests,代码行数:101,代码来源:ConnectionUtils.cs

示例5: SelectAndCreateConnection


//.........这里部分代码省略.........
                                {
                                    log.WriteLine("Slave should be promoted to master (but not done yet)...");
                                }
                            }
                            break;
                        case 1:
                            log.WriteLine("One master found; selecting");
                            preferred = masters[0];
                            break;
                        default:
                            log.WriteLine("Considering {0} masters...", masters.Count);
                            preferred = SelectWithTieBreak(log, masters, breakerScores);
                            break;
                    }
                }
                else
                {
                    // we have been instructed to change master server
                    preferred = masters.Concat(slaves)
                                       .FirstOrDefault(conn => (conn.Host + ":" + conn.Port) == newMaster);
                    if (preferred == null)
                    {
                        log.WriteLine("Selected new master not available: {0}", newMaster);
                    }
                    else
                    {
                        int errorCount = 0;
                        try
                        {
                            log.WriteLine("Promoting to master: {0}:{1}...", preferred.Host, preferred.Port);
                            preferred.Wait(preferred.Server.MakeMaster());
                            // if this is a master, we expect set/publish to work, even on 2.6
                            preferred.Strings.Set(0, tieBreakerKey, newMaster);
                            preferred.Wait(preferred.Publish(RedisMasterChangedChannel, newMaster));
                        }
                        catch (Exception ex)
                        {
                            log.WriteLine("\t{0}", ex.Message);
                            errorCount++;
                        }

                        if (errorCount == 0) // only make slaves if the master was happy
                        {
                            foreach (RedisConnection conn in masters.Concat(slaves))
                            {
                                if (conn == preferred) continue; // can't make self a slave!

                                try
                                {
                                    log.WriteLine("Enslaving: {0}:{1}...", conn.Host, conn.Port);

                                    // try to set the tie-breaker **first** in case of problems
                                    Task didSet = conn.Strings.Set(0, tieBreakerKey, newMaster);
                                    // and broadcast to anyone who thinks this is the master
                                    Task<long> didPublish = conn.Publish(RedisMasterChangedChannel, newMaster);
                                    // now make it a slave
                                    Task didEnslave = conn.Server.MakeSlave(preferred.Host, preferred.Port);
                                    // these are best-effort only; from 2.6, readonly slave servers may reject these commands
                                    try
                                    {
                                        conn.Wait(didSet);
                                    }
                                    catch
                                    {
                                    }
                                    try
开发者ID:jorik041,项目名称:booksleeve-unofficial,代码行数:67,代码来源:ConnectionUtils.cs

示例6: TestMassivePublishWithWithoutFlush

        private void TestMassivePublishWithWithoutFlush(RedisConnection conn, string caption)
        {
            const int loop = 100000;

            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();

            var tasks = new Task[loop];
            var withFlush = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
                tasks[i] = conn.Publish("foo", "bar");
            conn.WaitAll(tasks);
            withFlush.Stop();

            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            GC.WaitForPendingFinalizers();

            conn.SuspendFlush();
            var withoutFlush = Stopwatch.StartNew();
            for (int i = 0; i < loop; i++)
                tasks[i] = conn.Publish("foo", "bar");
            conn.ResumeFlush();
            conn.WaitAll(tasks);
            withoutFlush.Stop();

            Assert.Less(1, 2, "sanity check");
            Assert.Less(withoutFlush.ElapsedMilliseconds, withFlush.ElapsedMilliseconds, caption);
            Console.WriteLine("{2}: {0}ms (eager-flush) vs {1}ms (suspend-flush)",
                withFlush.ElapsedMilliseconds, withoutFlush.ElapsedMilliseconds, caption);
        }
开发者ID:raycode,项目名称:booksleeve,代码行数:30,代码来源:PubSub.cs


注:本文中的BookSleeve.RedisConnection.Publish方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。