示例#1
0
        static async Task Start()
        {
            Console.Title = "Sender";
            string connectionString = @"Data Source=(local)\MYDEV;Initial Catalog=NsbSamplesSqlOutbox;Integrated Security=True;Max Pool Size=100";
            var    storage          = new SqlSubscriptionStorage(() => new SqlConnection(connectionString), "WebApplication",
                                                                 new SqlDialect.MsSqlServer(), null);

            storage.Install().GetAwaiter().GetResult();

            //The system uses RabbitMQ transport
            var connectorConfig = new ConnectorConfiguration <RabbitMQTransport>(
                name: "WebApplication",
                sqlConnectionString: connectionString,
                customizeConnectedTransport: extensions =>
            {
                extensions.ConnectionString("host=localhost;username=guest;password=guest");
                extensions.UseConventionalRoutingTopology();
            },
                customizeConnectedInterface: configuration => { configuration.EnableMessageDrivenPublishSubscribe(storage); });

            connectorConfig.AutoCreateQueues();


            //Start the connector
            var connector = connectorConfig.CreateConnector();
            await connector.Start();

            Console.WriteLine("(Q) Quit (R) Rollback (Any other key) Write to TestTable and publish message");

            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();

                if (key.Key == ConsoleKey.Q)
                {
                    break;
                }

                using (var sqlConn = new SqlConnection(connectionString))
                {
                    await sqlConn.OpenAsync();

                    using (var tran = sqlConn.BeginTransaction())
                    {
                        var message = connector.GetSession(sqlConn, tran);

                        await message.Publish(new MyMessage { Message = $"Test {key.Key}" }).ConfigureAwait(false);

                        using (var command = new SqlCommand("INSERT INTO TestTable VALUES ('Test')", sqlConn, tran))
                        {
                            await command.ExecuteNonQueryAsync();
                        }

                        if (key.Key == ConsoleKey.R)
                        {
                            tran.Rollback(); // Simulate rollback
                        }
                        else
                        {
                            tran.Commit(); // Business as usual
                        }
                    }
                }
            }

            await connector.Stop();

            Console.ReadLine();
        }