├── .gitignore ├── LICENSE ├── README.md └── src ├── EmitLog ├── EmitLog.fsproj └── Program.fs ├── EmitLogDirect ├── EmitLogDirect.fsproj └── Program.fs ├── EmitLogTopic ├── EmitLogTopic.fsproj └── Program.fs ├── NewTask ├── NewTask.fsproj └── Program.fs ├── PublisherConfirms ├── Program.fs └── PublisherConfirms.fsproj ├── RPCClient ├── Program.fs └── RPCClient.fsproj ├── RPCServer ├── Program.fs └── RPCServer.fsproj ├── Receive ├── Program.fs └── Receive.fsproj ├── ReceiveLogs ├── Program.fs └── ReceiveLogs.fsproj ├── ReceiveLogsDirect ├── Program.fs └── ReceiveLogsDirect.fsproj ├── ReceiveLogsTopic ├── Program.fs └── ReceiveLogsTopic.fsproj ├── Send ├── Program.fs └── Send.fsproj └── Worker ├── Program.fs └── Worker.fsproj /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | .ionide/ 7 | 8 | # User-specific files 9 | *.rsuser 10 | *.suo 11 | *.user 12 | *.userosscache 13 | *.sln.docstates 14 | 15 | # User-specific files (MonoDevelop/Xamarin Studio) 16 | *.userprefs 17 | 18 | # Mono auto generated files 19 | mono_crash.* 20 | 21 | # Build results 22 | [Dd]ebug/ 23 | [Dd]ebugPublic/ 24 | [Rr]elease/ 25 | [Rr]eleases/ 26 | x64/ 27 | x86/ 28 | [Aa][Rr][Mm]/ 29 | [Aa][Rr][Mm]64/ 30 | bld/ 31 | [Bb]in/ 32 | [Oo]bj/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # StyleCop 67 | StyleCopReport.xml 68 | 69 | # Files built by Visual Studio 70 | *_i.c 71 | *_p.c 72 | *_h.h 73 | *.ilk 74 | *.meta 75 | *.obj 76 | *.iobj 77 | *.pch 78 | *.pdb 79 | *.ipdb 80 | *.pgc 81 | *.pgd 82 | *.rsp 83 | *.sbr 84 | *.tlb 85 | *.tli 86 | *.tlh 87 | *.tmp 88 | *.tmp_proj 89 | *_wpftmp.csproj 90 | *.log 91 | *.vspscc 92 | *.vssscc 93 | .builds 94 | *.pidb 95 | *.svclog 96 | *.scc 97 | 98 | # Chutzpah Test files 99 | _Chutzpah* 100 | 101 | # Visual C++ cache files 102 | ipch/ 103 | *.aps 104 | *.ncb 105 | *.opendb 106 | *.opensdf 107 | *.sdf 108 | *.cachefile 109 | *.VC.db 110 | *.VC.VC.opendb 111 | 112 | # Visual Studio profiler 113 | *.psess 114 | *.vsp 115 | *.vspx 116 | *.sap 117 | 118 | # Visual Studio Trace Files 119 | *.e2e 120 | 121 | # TFS 2012 Local Workspace 122 | $tf/ 123 | 124 | # Guidance Automation Toolkit 125 | *.gpState 126 | 127 | # ReSharper is a .NET coding add-in 128 | _ReSharper*/ 129 | *.[Rr]e[Ss]harper 130 | *.DotSettings.user 131 | 132 | # TeamCity is a build add-in 133 | _TeamCity* 134 | 135 | # DotCover is a Code Coverage Tool 136 | *.dotCover 137 | 138 | # AxoCover is a Code Coverage Tool 139 | .axoCover/* 140 | !.axoCover/settings.json 141 | 142 | # Visual Studio code coverage results 143 | *.coverage 144 | *.coveragexml 145 | 146 | # NCrunch 147 | _NCrunch_* 148 | .*crunch*.local.xml 149 | nCrunchTemp_* 150 | 151 | # MightyMoose 152 | *.mm.* 153 | AutoTest.Net/ 154 | 155 | # Web workbench (sass) 156 | .sass-cache/ 157 | 158 | # Installshield output folder 159 | [Ee]xpress/ 160 | 161 | # DocProject is a documentation generator add-in 162 | DocProject/buildhelp/ 163 | DocProject/Help/*.HxT 164 | DocProject/Help/*.HxC 165 | DocProject/Help/*.hhc 166 | DocProject/Help/*.hhk 167 | DocProject/Help/*.hhp 168 | DocProject/Help/Html2 169 | DocProject/Help/html 170 | 171 | # Click-Once directory 172 | publish/ 173 | 174 | # Publish Web Output 175 | *.[Pp]ublish.xml 176 | *.azurePubxml 177 | # Note: Comment the next line if you want to checkin your web deploy settings, 178 | # but database connection strings (with potential passwords) will be unencrypted 179 | *.pubxml 180 | *.publishproj 181 | 182 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 183 | # checkin your Azure Web App publish settings, but sensitive information contained 184 | # in these scripts will be unencrypted 185 | PublishScripts/ 186 | 187 | # NuGet Packages 188 | *.nupkg 189 | # NuGet Symbol Packages 190 | *.snupkg 191 | # The packages folder can be ignored because of Package Restore 192 | **/[Pp]ackages/* 193 | # except build/, which is used as an MSBuild target. 194 | !**/[Pp]ackages/build/ 195 | # Uncomment if necessary however generally it will be regenerated when needed 196 | #!**/[Pp]ackages/repositories.config 197 | # NuGet v3's project.json files produces more ignorable files 198 | *.nuget.props 199 | *.nuget.targets 200 | 201 | # Microsoft Azure Build Output 202 | csx/ 203 | *.build.csdef 204 | 205 | # Microsoft Azure Emulator 206 | ecf/ 207 | rcf/ 208 | 209 | # Windows Store app package directories and files 210 | AppPackages/ 211 | BundleArtifacts/ 212 | Package.StoreAssociation.xml 213 | _pkginfo.txt 214 | *.appx 215 | *.appxbundle 216 | *.appxupload 217 | 218 | # Visual Studio cache files 219 | # files ending in .cache can be ignored 220 | *.[Cc]ache 221 | # but keep track of directories ending in .cache 222 | !?*.[Cc]ache/ 223 | 224 | # Others 225 | ClientBin/ 226 | ~$* 227 | *~ 228 | *.dbmdl 229 | *.dbproj.schemaview 230 | *.jfm 231 | *.pfx 232 | *.publishsettings 233 | orleans.codegen.cs 234 | 235 | # Including strong name files can present a security risk 236 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 237 | #*.snk 238 | 239 | # Since there are multiple workflows, uncomment next line to ignore bower_components 240 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 241 | #bower_components/ 242 | 243 | # RIA/Silverlight projects 244 | Generated_Code/ 245 | 246 | # Backup & report files from converting an old project file 247 | # to a newer Visual Studio version. Backup files are not needed, 248 | # because we have git ;-) 249 | _UpgradeReport_Files/ 250 | Backup*/ 251 | UpgradeLog*.XML 252 | UpgradeLog*.htm 253 | ServiceFabricBackup/ 254 | *.rptproj.bak 255 | 256 | # SQL Server files 257 | *.mdf 258 | *.ldf 259 | *.ndf 260 | 261 | # Business Intelligence projects 262 | *.rdl.data 263 | *.bim.layout 264 | *.bim_*.settings 265 | *.rptproj.rsuser 266 | *- [Bb]ackup.rdl 267 | *- [Bb]ackup ([0-9]).rdl 268 | *- [Bb]ackup ([0-9][0-9]).rdl 269 | 270 | # Microsoft Fakes 271 | FakesAssemblies/ 272 | 273 | # GhostDoc plugin setting file 274 | *.GhostDoc.xml 275 | 276 | # Node.js Tools for Visual Studio 277 | .ntvs_analysis.dat 278 | node_modules/ 279 | 280 | # Visual Studio 6 build log 281 | *.plg 282 | 283 | # Visual Studio 6 workspace options file 284 | *.opt 285 | 286 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 287 | *.vbw 288 | 289 | # Visual Studio LightSwitch build output 290 | **/*.HTMLClient/GeneratedArtifacts 291 | **/*.DesktopClient/GeneratedArtifacts 292 | **/*.DesktopClient/ModelManifest.xml 293 | **/*.Server/GeneratedArtifacts 294 | **/*.Server/ModelManifest.xml 295 | _Pvt_Extensions 296 | 297 | # Paket dependency manager 298 | .paket/paket.exe 299 | paket-files/ 300 | 301 | # FAKE - F# Make 302 | .fake/ 303 | 304 | # CodeRush personal settings 305 | .cr/personal 306 | 307 | # Python Tools for Visual Studio (PTVS) 308 | __pycache__/ 309 | *.pyc 310 | 311 | # Cake - Uncomment if you are using it 312 | # tools/** 313 | # !tools/packages.config 314 | 315 | # Tabs Studio 316 | *.tss 317 | 318 | # Telerik's JustMock configuration file 319 | *.jmconfig 320 | 321 | # BizTalk build output 322 | *.btp.cs 323 | *.btm.cs 324 | *.odx.cs 325 | *.xsd.cs 326 | 327 | # OpenCover UI analysis results 328 | OpenCover/ 329 | 330 | # Azure Stream Analytics local run output 331 | ASALocalRun/ 332 | 333 | # MSBuild Binary and Structured Log 334 | *.binlog 335 | 336 | # NVidia Nsight GPU debugger configuration file 337 | *.nvuser 338 | 339 | # MFractors (Xamarin productivity tool) working folder 340 | .mfractor/ 341 | 342 | # Local History for Visual Studio 343 | .localhistory/ 344 | 345 | # BeatPulse healthcheck temp database 346 | healthchecksdb 347 | 348 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 349 | MigrationBackup/ 350 | 351 | # Ionide (cross platform F# VS Code tools) working folder 352 | .ionide/ 353 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Édgar Sánchez Gordón 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FsRabbitMQ-Tutorials 2 | F# implementation of [RabbitMQ tutorials](https://www.rabbitmq.com/getstarted.html), specifically based on the [C# samples](https://github.com/rabbitmq/rabbitmq-tutorials/tree/master/dotnet) available in github. Now we have all the Getting Started tutorials from the RabbitMQ site implemented: 3 | 4 | * The ["Hello World!" tutorial](https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html) 5 | * The src/Send folder contains the Sender console app 6 | * The src/Receive folder contains the Receive console app 7 | * The [Work queues tutorial](https://www.rabbitmq.com/tutorials/tutorial-two-dotnet.html) 8 | * The src/NewTask folder contains a console app that publishes a message to the task_queue 9 | * The src/Worker folder contains a console app that subscribes to the task_queue 10 | * The [Publish/Subscribe tutorial](https://www.rabbitmq.com/tutorials/tutorial-three-dotnet.html) 11 | * The src/EmitLog folder contains a console app that publishes a message to the logs exchange 12 | * The src/ReceiveLogs folder contains a console app that subscribes to the exchange with a temporary queue (many ReceiveLogs apps can be run simultaneously, each one will have its own temporary queue) 13 | * The [Routing tutorial](https://www.rabbitmq.com/tutorials/tutorial-four-dotnet.html) 14 | * The src/EmitLogDirect folder contains a console app that publishes a message to the direct_logs exchange using a severity level as routing key, e.g. `dotnet run warning "This is a warning!"` 15 | * The src/ReceiveLogsDirect folder contains a console app that subscribes to the exchange with a temporary queue and one or more routing keys, e.g. `dotnet run warning` (several ReceiveLogsDirect apps can be run simultaneously, each waiting for specific routing keys in a temporary queue) 16 | * The [Topics tutorial](https://www.rabbitmq.com/tutorials/tutorial-five-dotnet.html) 17 | * The src/EmitLogTopic folder contains a console app that publishes a message to the topic_logs exchange using a topic as routing key, e.g. `dotnet run kern.critical "A critical kernel error."` 18 | * The src/ReceiveLogsTopic folder contains a console app that subscribes to the exchange with a temporary queue and one or more topics as routing keys, e.g. `dotnet run kern.*` (several ReceiveLogsTopic apps can be run simultaneously, each waiting for specific topics in a temporary queue) 19 | * The [RPC tutorial](https://www.rabbitmq.com/tutorials/tutorial-six-dotnet.html) 20 | * The src/RPCServer folder contains a console app that waits for requests in the rpc_queue, when a request appears, the server does the job and send the result back using the queue from the `ReplyTo` property. The server must be started before any client, multiple servers can be started. 21 | * The src/RPCClient folder contains a console app that starts by creating a specific callback queue, each client has got its own callback queue. When the client sends a request, it sets the `ReplyTo` property to its own callback queue and the `CorrelationId` which is unique for every request. You invoke the client with `dotnet run 30` or any positive integer 22 | * The [Publish Confirms tutorial](https://www.rabbitmq.com/tutorials/tutorial-seven-dotnet.html) in the src/PublishConfirms folder. A single console app showing three ways for confirming that a published message was processed by the broker. To run the example all you have to do is type `dotnet run` inside the folder. 23 | 24 | All the examples assume a RabbitMQ server installation on the local computer. By default, to run any of the console apps you just have to get into the corresponding folder and type `dotnet run`, some tutorials have more specific instructions. 25 | 26 | Comments and feedback welcomed! 27 | -------------------------------------------------------------------------------- /src/EmitLog/EmitLog.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/EmitLog/Program.fs: -------------------------------------------------------------------------------- 1 | open RabbitMQ.Client 2 | open System 3 | open System.Text 4 | 5 | let getMessage (argv: string array) = 6 | if Array.length argv > 0 then 7 | String.Join (' ', argv) 8 | else 9 | "Hello World!" 10 | 11 | [] 12 | let main argv = 13 | let factory = ConnectionFactory (HostName = "localhost") 14 | use connection = factory.CreateConnection () 15 | use channel = connection.CreateModel () 16 | 17 | channel.ExchangeDeclare (exchange = "logs", ``type`` = ExchangeType.Fanout) 18 | 19 | let message = getMessage argv 20 | let body = ReadOnlyMemory (Encoding.UTF8.GetBytes message) 21 | channel.BasicPublish (exchange = "logs", routingKey = "", basicProperties = null, body = body) 22 | printfn " [x] Sent %s" message 23 | 24 | printfn " Press [Enter] to exit." 25 | Console.ReadLine () |> ignore 26 | 0 27 | -------------------------------------------------------------------------------- /src/EmitLogDirect/EmitLogDirect.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/EmitLogDirect/Program.fs: -------------------------------------------------------------------------------- 1 | open RabbitMQ.Client 2 | open System 3 | open System.Text 4 | 5 | [] 6 | let main argv = 7 | let factory = ConnectionFactory (HostName = "localhost") 8 | use connection = factory.CreateConnection () 9 | use channel = connection.CreateModel () 10 | 11 | channel.ExchangeDeclare (exchange = "direct_logs", ``type`` = ExchangeType.Direct) 12 | 13 | let severity = if Array.length argv > 0 then Array.head argv else "info" 14 | let message = if Array.length argv > 1 then 15 | String.Join (" ", Array.skip 1 argv) 16 | else 17 | "Hello World!" 18 | 19 | let body = ReadOnlyMemory (Encoding.UTF8.GetBytes message) 20 | channel.BasicPublish (exchange = "direct_logs", routingKey = severity, basicProperties = null, body = body) 21 | printfn " [x] Sent '%s': '%s'" severity message 22 | 23 | printfn " Press [Enter] to exit." 24 | Console.ReadLine () |> ignore 25 | 0 26 | -------------------------------------------------------------------------------- /src/EmitLogTopic/EmitLogTopic.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/EmitLogTopic/Program.fs: -------------------------------------------------------------------------------- 1 | open RabbitMQ.Client 2 | open System 3 | open System.Text 4 | 5 | [] 6 | let main argv = 7 | let factory = ConnectionFactory (HostName = "localhost") 8 | use connection = factory.CreateConnection () 9 | use channel = connection.CreateModel () 10 | 11 | channel.ExchangeDeclare (exchange = "topic_logs", ``type`` = ExchangeType.Topic) 12 | 13 | let routingKey = if Array.length argv > 0 then Array.head argv else "anonymous.info" 14 | let message = if Array.length argv > 1 then 15 | String.Join (" ", Array.skip 1 argv) 16 | else 17 | "Hello World!" 18 | 19 | let body = ReadOnlyMemory (Encoding.UTF8.GetBytes message) 20 | channel.BasicPublish (exchange = "topic_logs", routingKey = routingKey, basicProperties = null, body = body) 21 | printfn " [x] Sent '%s': '%s'" routingKey message 22 | 23 | 0 24 | -------------------------------------------------------------------------------- /src/NewTask/NewTask.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/NewTask/Program.fs: -------------------------------------------------------------------------------- 1 | open RabbitMQ.Client 2 | open System 3 | open System.Text 4 | 5 | let getMessage (argv: string array) = 6 | if Array.length argv > 0 then 7 | String.Join (' ', argv) 8 | else 9 | "Hello World!" 10 | 11 | [] 12 | let main argv = 13 | let factory = ConnectionFactory (HostName = "localhost") 14 | use connection = factory.CreateConnection () 15 | use channel = connection.CreateModel () 16 | 17 | channel.QueueDeclare (queue = "task_queue", durable = true, exclusive = false, autoDelete = false, arguments = null) |> ignore 18 | 19 | let message = getMessage argv 20 | let body = ReadOnlyMemory (Encoding.UTF8.GetBytes message) 21 | 22 | let properties = channel.CreateBasicProperties () 23 | properties.Persistent <- true 24 | 25 | channel.BasicPublish (exchange = "", routingKey = "task_queue", basicProperties = properties, body = body) 26 | printfn " [x] Sent %s" message 27 | 28 | printfn " Press [Enter] to exit." 29 | Console.ReadLine () |> ignore 30 | 0 31 | -------------------------------------------------------------------------------- /src/PublisherConfirms/Program.fs: -------------------------------------------------------------------------------- 1 | open System 2 | open System.Collections.Concurrent 3 | open System.Diagnostics 4 | open System.Linq 5 | open System.Text 6 | open System.Threading 7 | open RabbitMQ.Client 8 | 9 | let messageCount = 50_000 10 | 11 | let createConnection () = 12 | let factory = ConnectionFactory (HostName = "localhost") 13 | factory.CreateConnection () 14 | 15 | let publishMessagesIndividually () = 16 | use connection = createConnection () 17 | use channel = connection.CreateModel () 18 | 19 | let queueName = channel.QueueDeclare().QueueName 20 | channel.ConfirmSelect () 21 | 22 | let timer = Stopwatch () 23 | timer.Start () 24 | for i in 0 .. messageCount - 1 do 25 | let body = ReadOnlyMemory (Encoding.UTF8.GetBytes (string i)) 26 | channel.BasicPublish (exchange = "", routingKey = queueName, basicProperties = null, body = body) 27 | channel.WaitForConfirmsOrDie (TimeSpan (0, 0, 5)) 28 | 29 | timer.Stop () 30 | printfn "Published %d messages individually in %d ms" messageCount timer.ElapsedMilliseconds 31 | 32 | let publishMessagesInBatch () = 33 | use connection = createConnection () 34 | use channel = connection.CreateModel () 35 | 36 | let queueName = channel.QueueDeclare().QueueName 37 | channel.ConfirmSelect () 38 | 39 | let batchSize = 100 40 | 41 | let rec processBatches countInBatch count = 42 | if count < messageCount then 43 | let body = ReadOnlyMemory (Encoding.UTF8.GetBytes (string count)) 44 | channel.BasicPublish (exchange = "", routingKey = queueName, basicProperties = null, body = body) 45 | if countInBatch < batchSize then 46 | processBatches (countInBatch + 1) (count + 1) 47 | else 48 | channel.WaitForConfirmsOrDie (TimeSpan (0, 0, 5)) 49 | processBatches 0 (count + 1) 50 | else 51 | countInBatch 52 | 53 | let timer = Stopwatch () 54 | timer.Start () 55 | if processBatches 0 0 > 0 then 56 | channel.WaitForConfirmsOrDie (TimeSpan (0, 0, 5)) 57 | timer.Stop () 58 | printfn "Published %d messages in batch in %d ms" messageCount timer.ElapsedMilliseconds 59 | 60 | let rec waitUntil waited numberOfMilliSeconds condition = 61 | if condition () || waited >= numberOfMilliSeconds then 62 | condition () 63 | else 64 | Thread.Sleep 100 65 | waitUntil (waited + 100) numberOfMilliSeconds condition 66 | 67 | let handlePublishConfirmsAsynchronously () = 68 | use connection = createConnection () 69 | use channel = connection.CreateModel () 70 | 71 | let queueName = channel.QueueDeclare().QueueName 72 | channel.ConfirmSelect () 73 | 74 | let outstandingConfirms = ConcurrentDictionary () 75 | 76 | let cleanOutstandingConfirms sequenceNumber multiple = 77 | if multiple then 78 | outstandingConfirms.Where (fun k -> k.Key <= sequenceNumber) 79 | |> Seq.iter (fun entry -> outstandingConfirms.TryRemove entry.Key |> ignore) 80 | else 81 | outstandingConfirms.TryRemove sequenceNumber |> ignore 82 | 83 | channel.BasicAcks.AddHandler (fun _ ea -> cleanOutstandingConfirms ea.DeliveryTag ea.Multiple) 84 | channel.BasicNacks.AddHandler (fun _ ea -> 85 | let _, body = outstandingConfirms.TryGetValue ea.DeliveryTag 86 | printfn "Message with body %s has been nack-ed. Sequence number: %d, multiple: %b" body ea.DeliveryTag ea.Multiple 87 | cleanOutstandingConfirms ea.DeliveryTag ea.Multiple ) 88 | 89 | let timer = Stopwatch () 90 | timer.Start () 91 | for i in 0 .. messageCount - 1 do 92 | let body = string i 93 | outstandingConfirms.TryAdd (channel.NextPublishSeqNo, string i) |> ignore 94 | channel.BasicPublish (exchange = "", routingKey = queueName, basicProperties = null, body = ReadOnlyMemory (Encoding.UTF8.GetBytes body)) 95 | 96 | if not (waitUntil 0 (60*1000) (fun () -> outstandingConfirms.IsEmpty)) then 97 | raise (Exception ("All messages could not be confirmed in 60 seconds")) 98 | 99 | timer.Stop () 100 | printfn "Published %d messages and handled confirm asynchronously %d ms" messageCount timer.ElapsedMilliseconds 101 | 102 | [< EntryPoint >] 103 | let main _ = 104 | publishMessagesIndividually () 105 | publishMessagesInBatch () 106 | handlePublishConfirmsAsynchronously () 107 | 108 | 0 -------------------------------------------------------------------------------- /src/PublisherConfirms/PublisherConfirms.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/RPCClient/Program.fs: -------------------------------------------------------------------------------- 1 | open System 2 | open System.Collections.Concurrent 3 | open System.Text 4 | open System.Threading 5 | open System.Threading.Tasks 6 | open RabbitMQ.Client 7 | open RabbitMQ.Client.Events 8 | 9 | type RpcClient () = 10 | let queueName = "rpc_queue" 11 | 12 | let factory = ConnectionFactory (HostName = "localhost") 13 | let connection = factory.CreateConnection () 14 | let channel = connection.CreateModel () 15 | let replyQueueName = channel.QueueDeclare().QueueName 16 | let consumer = EventingBasicConsumer (channel) 17 | let callbackMapper = ConcurrentDictionary> () 18 | 19 | do 20 | consumer.Received.AddHandler (fun _ ea -> 21 | match callbackMapper.TryRemove ea.BasicProperties.CorrelationId with 22 | | true, tcs -> ea.Body.ToArray () |> Encoding.UTF8.GetString |> tcs.TrySetResult |> ignore 23 | | _ -> () ) 24 | 25 | member __.CallAsync (message: string, ?cancellationToken: CancellationToken) = 26 | let correlationId = Guid.NewGuid().ToString () 27 | let props = channel.CreateBasicProperties (CorrelationId = correlationId, ReplyTo = replyQueueName) 28 | let messageBytes = ReadOnlyMemory (Encoding.UTF8.GetBytes message) 29 | let tcs = TaskCompletionSource () 30 | callbackMapper.TryAdd (correlationId, tcs) |> ignore 31 | 32 | channel.BasicPublish(exchange = "", routingKey = queueName, basicProperties = props, body = messageBytes) 33 | 34 | channel.BasicConsume(consumer = consumer, queue = replyQueueName, autoAck = true) |> ignore 35 | 36 | let canToken = match cancellationToken with Some token -> token| None -> CancellationToken.None 37 | canToken.Register (fun _ -> callbackMapper.TryRemove correlationId |> ignore) |> ignore 38 | tcs.Task 39 | 40 | member __.Close () = 41 | connection.Close () 42 | 43 | let invokeAsync n = 44 | async { 45 | let rpcClient = RpcClient () 46 | 47 | printfn " [x] Requesting fib(%s)" n 48 | let! response = rpcClient.CallAsync n |> Async.AwaitTask 49 | printfn " [.] Got '%s'" response 50 | 51 | rpcClient.Close () 52 | } 53 | 54 | [] 55 | let main argv = 56 | printfn "RPC Client" 57 | let n = if Array.isEmpty argv then "30" else Array.head argv 58 | async { do! invokeAsync n } |> Async.RunSynchronously 59 | 60 | printfn " Press [Enter] to exit." 61 | Console.ReadLine () |> ignore 62 | 0 63 | -------------------------------------------------------------------------------- /src/RPCClient/RPCClient.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/RPCServer/Program.fs: -------------------------------------------------------------------------------- 1 | open System 2 | open System.Text 3 | open RabbitMQ.Client 4 | open RabbitMQ.Client.Events 5 | 6 | /// Assumes only valid positive integer input. 7 | /// Don't expect this one to work for big numbers, and it's probably the slowest recursive implementation possible. 8 | let rec fib n = 9 | if n = 1 || n = 0 then 10 | n 11 | else 12 | fib (n - 1) + fib (n - 2) 13 | 14 | [] 15 | let main _ = 16 | let factory = ConnectionFactory (HostName = "localhost") 17 | use connection = factory.CreateConnection () 18 | use channel = connection.CreateModel () 19 | 20 | channel.QueueDeclare (queue = "rpc_queue", durable = false, exclusive = false, autoDelete = false, arguments = null) |> ignore 21 | channel.BasicQos (prefetchSize = 0u, prefetchCount = 1us, ``global`` = false) 22 | let consumer = EventingBasicConsumer (channel) 23 | channel.BasicConsume (queue = "rpc_queue", autoAck = false, consumer = consumer) |> ignore 24 | printfn " [*] Awaiting RPC requests" 25 | 26 | consumer.Received.AddHandler (fun _ ea -> 27 | let body = ea.Body.ToArray () 28 | let message = Encoding.UTF8.GetString body 29 | let response = 30 | match Int32.TryParse message with 31 | | true, n -> 32 | printfn " [.] fib(%s)" message 33 | sprintf "%d" (fib n) 34 | | _ -> 35 | "" 36 | 37 | let responseBytes = ReadOnlyMemory (Encoding.UTF8.GetBytes response) 38 | let props = ea.BasicProperties 39 | let replyProps = channel.CreateBasicProperties (CorrelationId = props.CorrelationId) 40 | channel.BasicPublish (exchange = "", routingKey = props.ReplyTo, basicProperties = replyProps, body = responseBytes) 41 | channel.BasicAck (deliveryTag = ea.DeliveryTag, multiple = false) ) 42 | 43 | printfn " Press [Enter] to exit." 44 | Console.ReadLine () |> ignore 45 | 0 46 | -------------------------------------------------------------------------------- /src/RPCServer/RPCServer.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/Receive/Program.fs: -------------------------------------------------------------------------------- 1 | open RabbitMQ.Client 2 | open RabbitMQ.Client.Events 3 | open System 4 | open System.Text 5 | 6 | [] 7 | let main _ = 8 | let factory = ConnectionFactory (HostName = "localhost") 9 | use connection = factory.CreateConnection () 10 | use channel = connection.CreateModel () 11 | 12 | channel.QueueDeclare (queue = "hello", durable = false, exclusive = false, autoDelete = false, arguments = null) |> ignore 13 | printfn " [*] Waiting for messages." 14 | 15 | let consumer = EventingBasicConsumer (channel) 16 | consumer.Received.AddHandler (fun _ ea -> 17 | let body = ea.Body.ToArray () 18 | let message = Encoding.UTF8.GetString body 19 | printfn " [x] Received %s" message ) 20 | channel.BasicConsume (queue = "hello", autoAck = true, consumer = consumer) |> ignore 21 | 22 | printfn " Press [Enter] to exit." 23 | Console.ReadLine () |> ignore 24 | 0 25 | -------------------------------------------------------------------------------- /src/Receive/Receive.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/ReceiveLogs/Program.fs: -------------------------------------------------------------------------------- 1 | open RabbitMQ.Client 2 | open RabbitMQ.Client.Events 3 | open System 4 | open System.Text 5 | 6 | [] 7 | let main _ = 8 | let factory = ConnectionFactory (HostName = "localhost") 9 | use connection = factory.CreateConnection () 10 | use channel = connection.CreateModel () 11 | 12 | channel.ExchangeDeclare (exchange = "logs", ``type`` = ExchangeType.Fanout) 13 | 14 | let queueName = channel.QueueDeclare().QueueName 15 | channel.QueueBind (queue = queueName, exchange = "logs", routingKey = "") 16 | printfn " [*] Waiting for logs." 17 | 18 | let consumer = EventingBasicConsumer (channel) 19 | consumer.Received.AddHandler (fun _ ea -> 20 | let body = ea.Body.ToArray () 21 | let message = Encoding.UTF8.GetString body 22 | printfn " [x] Received %s" message ) 23 | 24 | channel.BasicConsume (queue = queueName, autoAck = true, consumer = consumer) |> ignore 25 | 26 | printfn " Press [Enter] to exit." 27 | Console.ReadLine () |> ignore 28 | 0 29 | -------------------------------------------------------------------------------- /src/ReceiveLogs/ReceiveLogs.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/ReceiveLogsDirect/Program.fs: -------------------------------------------------------------------------------- 1 | open RabbitMQ.Client 2 | open RabbitMQ.Client.Events 3 | open System 4 | open System.Text 5 | 6 | [] 7 | let main argv = 8 | let factory = ConnectionFactory (HostName = "localhost") 9 | use connection = factory.CreateConnection () 10 | use channel = connection.CreateModel () 11 | 12 | let exitCode = 13 | if Array.length argv < 1 then 14 | eprintfn "Usage: %s [info] [warning] [error]" (Environment.GetCommandLineArgs().[0]) 15 | 1 16 | else 17 | channel.ExchangeDeclare (exchange = "direct_logs", ``type`` = ExchangeType.Direct) 18 | let queueName = channel.QueueDeclare().QueueName 19 | 20 | for severity in argv do 21 | channel.QueueBind (queue = queueName, exchange = "direct_logs", routingKey = severity) 22 | 23 | printfn " [*] Waiting for messages." 24 | 25 | let consumer = EventingBasicConsumer (channel) 26 | consumer.Received.AddHandler (fun _ ea -> 27 | let body = ea.Body.ToArray () 28 | let message = Encoding.UTF8.GetString body 29 | let routingKey = ea.RoutingKey 30 | printfn " [x] Received '%s': '%s'" routingKey message ) 31 | 32 | channel.BasicConsume (queue = queueName, autoAck = true, consumer = consumer) |> ignore 33 | 0 34 | 35 | printfn " Press [Enter] to exit." 36 | Console.ReadLine () |> ignore 37 | exitCode 38 | -------------------------------------------------------------------------------- /src/ReceiveLogsDirect/ReceiveLogsDirect.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/ReceiveLogsTopic/Program.fs: -------------------------------------------------------------------------------- 1 | open RabbitMQ.Client 2 | open RabbitMQ.Client.Events 3 | open System 4 | open System.Text 5 | 6 | [] 7 | let main argv = 8 | let factory = ConnectionFactory (HostName = "localhost") 9 | use connection = factory.CreateConnection () 10 | use channel = connection.CreateModel () 11 | 12 | let exitCode = 13 | if Array.length argv < 1 then 14 | eprintfn "Usage: %s [binding_key...]" (Environment.GetCommandLineArgs().[0]) 15 | 1 16 | else 17 | channel.ExchangeDeclare (exchange = "topic_logs", ``type`` = ExchangeType.Topic) 18 | let queueName = channel.QueueDeclare().QueueName 19 | 20 | for bindingKey in argv do 21 | channel.QueueBind (queue = queueName, exchange = "topic_logs", routingKey = bindingKey) 22 | 23 | printfn " [*] Waiting for messages. To exit press Control-C" 24 | 25 | let consumer = EventingBasicConsumer (channel) 26 | consumer.Received.AddHandler (fun _ ea -> 27 | let body = ea.Body.ToArray () 28 | let message = Encoding.UTF8.GetString body 29 | let routingKey = ea.RoutingKey 30 | printfn " [x] Received '%s': '%s'" routingKey message ) 31 | 32 | channel.BasicConsume (queue = queueName, autoAck = true, consumer = consumer) |> ignore 33 | 0 34 | 35 | printfn " Press [Enter] to exit." 36 | Console.ReadLine () |> ignore 37 | exitCode 38 | -------------------------------------------------------------------------------- /src/ReceiveLogsTopic/ReceiveLogsTopic.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/Send/Program.fs: -------------------------------------------------------------------------------- 1 | open RabbitMQ.Client 2 | open System 3 | open System.Text 4 | 5 | [] 6 | let main _ = 7 | let factory = ConnectionFactory (HostName = "localhost") 8 | use connection = factory.CreateConnection () 9 | use channel = connection.CreateModel () 10 | 11 | channel.QueueDeclare (queue = "hello", durable = false, exclusive = false, autoDelete = false, arguments = null) |> ignore 12 | 13 | let message = "Hello World!" 14 | let body = ReadOnlyMemory(Encoding.UTF8.GetBytes message) 15 | 16 | channel.BasicPublish (exchange = "", routingKey = "hello", basicProperties = null, body = body) 17 | printfn " [x] Sent %s" message 18 | 19 | printfn " Press [Enter] to exit." 20 | Console.ReadLine () |> ignore 21 | 0 22 | -------------------------------------------------------------------------------- /src/Send/Send.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /src/Worker/Program.fs: -------------------------------------------------------------------------------- 1 | open RabbitMQ.Client 2 | open RabbitMQ.Client.Events 3 | open System 4 | open System.Text 5 | open System.Threading 6 | 7 | [] 8 | let main _ = 9 | let factory = ConnectionFactory (HostName = "localhost") 10 | use connection = factory.CreateConnection () 11 | use channel = connection.CreateModel () 12 | 13 | channel.QueueDeclare (queue = "task_queue", durable = true, exclusive = false, autoDelete = false, arguments = null) |> ignore 14 | channel.BasicQos (prefetchSize = 0u, prefetchCount = 1us, ``global`` = false) 15 | printfn " [*] Waiting for messages." 16 | 17 | let consumer = EventingBasicConsumer (channel) 18 | consumer.Received.AddHandler (fun _ ea -> 19 | let body = ea.Body.ToArray () 20 | let message = Encoding.UTF8.GetString body 21 | printfn " [x] Received %s" message 22 | 23 | let dots = message.Split('.').Length - 1 24 | Thread.Sleep (dots * 1000) 25 | printfn " [x] Done" 26 | 27 | // here channel could also be accessed as ((EventingBasicConsumer)sender).Model 28 | channel.BasicAck (deliveryTag = ea.DeliveryTag, multiple = false) ) 29 | 30 | channel.BasicConsume (queue = "task_queue", autoAck = false, consumer = consumer) |> ignore 31 | 32 | printfn " Press [Enter] to exit." 33 | Console.ReadLine () |> ignore 34 | 0 35 | -------------------------------------------------------------------------------- /src/Worker/Worker.fsproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | --------------------------------------------------------------------------------