Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
NSERVICEBUSInspired by: The course authored by Udi Dahan                 Oslo/Fagdag          Espen Ekvang/Tomas Jansson  ...
AGENDA                   2• Intro• Messaging and queues• Testing• SOA• Saga
INTRO                                  4• Fallacies of distributed computing• Why NServiceBus?• Bus vs. Broker• Service or...
FALLACIES OF DISTRIBUTED COMPUTING                       51.   The network is reliable2.   Latency isn’t a problem3.   Ban...
WHY NSERVICEBUS                                                                      61.   The network is reliable2.   Lat...
BUS VS. BROKER                                                         7•    Bus is not necessarily physically separate•  ...
TENETS OF SERVICE ORIENTATION                    8•   Services are autonomous•   Share contract & schema, not class or typ...
LAYERS & COUPLING                                    9                                  Tight coupling                    ...
WHEN CAN I WRITE SOME CODE?                                               10• Getting started  •   New class library  •   ...
EXERCISES     11HELLO WORLDLOGGING
MESSAGING AND QUEUES           12• Store & forward• Dangers of store & forward• Request/Response• Messaging and NServiceBu...
STORE & FORWARD                                                13                                SERVER                   ...
DANGERS OF STORE & FORWARD                                                           14• If target is offline for an exten...
REQUEST/RESPONSE                                                     15                               SERVER              ...
REQUEST/RESPONSE                                                                  16• Message is sent from the server to t...
WARNING! THIS IS NOT RPC                                                                17• Do NOT try to implement regula...
MESSAGING AND NSERVICEBUS                  18                       SERVER                       MSMQ            OUTGOING ...
DEFINE A MESSAGE                                                         19• Preferably inherit from IEvent or ICommand• U...
INSTANTIATE A MESSAGE                                20• var myMessage = new MyMessage();• var myMessage = Bus.CreateInsta...
SEND A MESSAGE                                               21Bus.Send(messageObject);Can instantiate and send together (...
SPECIFY DESTINATION                                                    221. Bus.Send(destination, messages);   Requires th...
HANDLE A MESSAGE                                                             23Write a class that implements IHandleMessag...
CONFIGURING AN ENDPOINT                                                                  24When configuring an endpoint in...
EXERCISES                      25ONE-WAY MESSAGING (CLIENT)PROCESSING MESSAGES (SERVER)EXCEPTIONS
UNIT TESTING MESSAGE HANDLERS                                                     26Available from NuGet usingInstall-Pack...
EXERCISE       27UNIT TESTING
SAGA                 28• Definition• Saga declaration• Saga ending• Saga testing• Exercise
SAGA - DEFINITION                                                                29A Saga:•   Is a pattern for implementin...
SAGA - DECLARATION                                                                30public class MyPolicy : Saga<MyPolicyD...
SAGA – DECLARATION CONT.                               31public class MyPolicyData : ISagaEntity{       public Guid Id { g...
ENDING A SAGA                                                                        32MarkAsComplete();•   Can call this ...
UNIT TESTING A SAGA                                          33Test.Saga<MyPolicy>()    .ExpectPublish<Message1>(/* check ...
EXERCISE - SAGAS ROCK   34
EXTRA EXERCISES               35TIMEOUTCUSTOM XML NAMESPACECONFIGURABLE ROUTINGDEPENDENCY INJECTIONWEB-APP HOSTINGFULL DUP...
Upcoming SlideShare
Loading in …5
×

NServiceBus workshop presentation

1,595 views

Published on

Espen Ekvang and I had a one day workshop internally at BEKK, and this is the presentation we made for the workshop.

  • Be the first to comment

  • Be the first to like this

NServiceBus workshop presentation

  1. 1. NSERVICEBUSInspired by: The course authored by Udi Dahan Oslo/Fagdag Espen Ekvang/Tomas Jansson 01/03/2013
  2. 2. AGENDA 2• Intro• Messaging and queues• Testing• SOA• Saga
  3. 3. INTRO 4• Fallacies of distributed computing• Why NServiceBus?• Bus vs. Broker• Service orientation• Excercises
  4. 4. FALLACIES OF DISTRIBUTED COMPUTING 51. The network is reliable2. Latency isn’t a problem3. Bandwidth isn’t a problem4. The network is secure5. The topology won’t change6. The administrator will know what to do7. Transport cost isn’t a problem8. The network is homogeneous Cant’ assume WHEN the message will arrive, IF AT ALL
  5. 5. WHY NSERVICEBUS 61. The network is reliable2. Latency isn’t a problem NServiceBus addresses the first five directly3. Bandwidth isn’t a problem4. The network is secure5. The topology won’t change6. The administrator will know what to do7. Transport cost isn’t a problem8. The network is homogeneousThe most developer-friendly service bus for SOA on .NET
  6. 6. BUS VS. BROKER 7• Bus is not necessarily physically separate• Simpler; no routing or service fail over• No single point of failure App App Buss.dll Broker App App Buss.dll Buss.dll App App
  7. 7. TENETS OF SERVICE ORIENTATION 8• Services are autonomous• Share contract & schema, not class or type• Boundaries are explicit• Compatibitility is base on Policy
  8. 8. LAYERS & COUPLING 9 Tight coupling Loose coupling Sales Shipping CRM UI BL DAL DB Referential Integrity Reintroduces coupling
  9. 9. WHEN CAN I WRITE SOME CODE? 10• Getting started • New class library • Install-Package NServiceBus.Host• Logging • NServiceBus uses log4net, you can configure logging in app.config • Default output is console
  10. 10. EXERCISES 11HELLO WORLDLOGGING
  11. 11. MESSAGING AND QUEUES 12• Store & forward• Dangers of store & forward• Request/Response• Messaging and NServiceBus• Exercises
  12. 12. STORE & FORWARD 13 SERVER MSMQ OUTGOING INCOMING Store & Forward writes to disk Resilient in the face of failures MSMQ OUTGOING INCOMING CLIENT
  13. 13. DANGERS OF STORE & FORWARD 14• If target is offline for an extended period of timemessages can fill up the disk • Can cause a server to crash• Especially problematic in B2B integration • 1 MB/message, 100 message/sec = 6GB/minute• Solution – discard messages after a while • Use [TimeToBeReceived("00:01:00")] on the message definition
  14. 14. REQUEST/RESPONSE 15 SERVER MSMQ OUTGOING INCOMINGClient can’t assumewhen a response Equivalent to 2will arrive, if at all one-way messages MSMQ OUTGOING INCOMING CLIENT
  15. 15. REQUEST/RESPONSE 16• Message is sent from the server to the client’s queue If the client is offline, message sits in the server machine’s outgoing queue• Client is not blocked until response arrives• If two requests were sent, responses may arrive out of order
  16. 16. WARNING! THIS IS NOT RPC 17• Do NOT try to implement regular request/response patterns on top of messaging• The client should be designed so that it can continue operating if a response never comesDifferences from RPC• RPC is easy to code • After invoking a web service • Next line of code assumes we’ve got a response• RPC problems • Can’t reason about the time between one line of code and another• Messaging makes this all explicit
  17. 17. MESSAGING AND NSERVICEBUS 18 SERVER MSMQ OUTGOING INCOMING Transaction MSMQ OUTGOING INCOMING CLIENT
  18. 18. DEFINE A MESSAGE 19• Preferably inherit from IEvent or ICommand• Use IMessage when replying using Bus.Reply()• Also possible to define your own convention • Configure.DefiningMessagesAs(t=>MyOwnConvention(t))• Add properties like a regular class/interface• Keep contract definintions in their own assembly/projectpublic class MyEvent: IEvent {}
  19. 19. INSTANTIATE A MESSAGE 20• var myMessage = new MyMessage();• var myMessage = Bus.CreateInstance<MyMessage>();
  20. 20. SEND A MESSAGE 21Bus.Send(messageObject);Can instantiate and send together (useful for interfaces):Bus.Send<IMessage>((message) =>{ message.Prop1 = value1; message.Prop2 = value2;});
  21. 21. SPECIFY DESTINATION 221. Bus.Send(destination, messages); Requires that application manages routing2. Configure destination for message type. In <UnicastBusConfig>, under <MessageEndpointMappings> specify one of the following: - <add Messages="assembly" Endpoint="destination"/> - <add Messages="type" Endpoint="destination"/>3. Specify destination using - QueueName@ServerName , or - Just QueueName for the same machine
  22. 22. HANDLE A MESSAGE 23Write a class that implements IHandleMessages<T> where T is a message typepublic class MyHandler : IHandleMessages<MyMessage>{ public void Handle(MyMessage message) { }}Remember to specify in <UnicastBusConfig>, under<MessageEndpointMappings> one of the following:- <add Messages="assembly" Endpoint="source"/>- <add Messages="type" Endpoint="source"/>
  23. 23. CONFIGURING AN ENDPOINT 24When configuring an endpoint inherit from1. Using AsA_Client will - use non-transactional MsmqTransport - purge its queue of messages on startup - processes messages using its own permissions, not those of the message sender2. Using AsA_Server will - use transactional MsmqTransport - not purge its queue of messages on startup, hence fault-tolerant - processes messages using the permissions of the sender (impersonation)3. Using AsA_Publisher will - extends AsA_Server - indicates to the infrastructure that a storage for subscription request is to be set up
  24. 24. EXERCISES 25ONE-WAY MESSAGING (CLIENT)PROCESSING MESSAGES (SERVER)EXCEPTIONS
  25. 25. UNIT TESTING MESSAGE HANDLERS 26Available from NuGet usingInstall-Package NServiceBus.TestingProvides the ability to set expectations around how message handlers handle messages• Expect: Send, Reply, Publish, etc...Test.Initialize();Test.Handler<MyHandler>() .ExpectPublish<MyMessage>(message => message.Prop1 == value1) .OnMessage<SomeEvent>(someEvent => { someEvent.Prop1 = inputValue1; });
  26. 26. EXERCISE 27UNIT TESTING
  27. 27. SAGA 28• Definition• Saga declaration• Saga ending• Saga testing• Exercise
  28. 28. SAGA - DEFINITION 29A Saga:• Is a pattern for implementing long-lived transaction by using a series of shorter transactions• Holds relevant state to needed to process mulitple messages in a ”saga entity”• Are initiated by a message (event/command)
  29. 29. SAGA - DECLARATION 30public class MyPolicy : Saga<MyPolicyData>, IAmStartedByMessages<MyMessage1>, IHandleMessages<MyMessage2>{ public void Handle(MyMessage1 order) public void Handle(MyMessage2 order)}• Methods are like regular message handling logic• Sagas can be started by multiple messages (IAmStartedByMessages<T>)• First messages should start saga, following messages should be processed by the same one
  30. 30. SAGA – DECLARATION CONT. 31public class MyPolicyData : ISagaEntity{ public Guid Id { get; set; } public string Originator { get; set; } public string OriginalMessageId { get; set; }}
  31. 31. ENDING A SAGA 32MarkAsComplete();• Can call this from any method• Causes the saga to be deleted• Any data that you want retained should be sent on (or published) via a message
  32. 32. UNIT TESTING A SAGA 33Test.Saga<MyPolicy>() .ExpectPublish<Message1>(/* check values */) .ExpectSend<Message2>(/* check values */) .ExpectReplyToOriginator<Message3>(/* check values */) .When(saga => saga.Handle(myMessage));/* check values */message => return(message.Data == someValue);
  33. 33. EXERCISE - SAGAS ROCK 34
  34. 34. EXTRA EXERCISES 35TIMEOUTCUSTOM XML NAMESPACECONFIGURABLE ROUTINGDEPENDENCY INJECTIONWEB-APP HOSTINGFULL DUPLEXDISTRIBUTION GROUP EXERCISE

×