Debian Codegraph @

go/examples/electron/receive.go

raw
1 /*
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements. See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership. The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License. You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing,
13 software distributed under the License is distributed on an
14 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 KIND, either express or implied. See the License for the
16 specific language governing permissions and limitations
17 under the License.
18 */
19
20 package main
21
22 import (
23 "flag"
24 "fmt"
25 "log"
26 "os"
27 "strings"
28 "sync"
29
30 "github.com/apache/qpid-proton/go/pkg/amqp"
31 "github.com/apache/qpid-proton/go/pkg/electron"
32 )
33
34 // Usage and command-line flags
35 func usage() {
36 fmt.Fprintf(os.Stderr, `Usage: %s url [url ...]
37 Receive messages from all URLs concurrently and print them.
38 URLs are of the form "amqp://<host>:<port>/<amqp-address>"
39 `, os.Args[0])
40 flag.PrintDefaults()
41 }
42
43 var count = flag.Int("count", 1, "Stop after receiving this many messages in total")
44 var prefetch = flag.Int("prefetch", 0, "enable a pre-fetch window for flow control")
45 var debug = flag.Bool("debug", false, "Print detailed debug output")
46 var debugf = func(format string, data ...interface{}) {} // Default no debugging output
47
48 func main() {
49 flag.Usage = usage
50 flag.Parse()
51
52 if *debug {
53 debugf = func(format string, data ...interface{}) { log.Printf(format, data...) }
54 }
55 urls := flag.Args() // Non-flag arguments are URLs to receive from
56 if len(urls) == 0 {
57 log.Println("No URL provided")
58 usage()
59 os.Exit(1)
60 }
61
62 messages := make(chan amqp.Message) // Channel for messages from goroutines to main()
63 defer close(messages)
64
65 var wait sync.WaitGroup // Used by main() to wait for all goroutines to end.
66 wait.Add(len(urls)) // Wait for one goroutine per URL.
67
68 container := electron.NewContainer(fmt.Sprintf("receive[%v]", os.Getpid()))
69 connections := make(chan electron.Connection, len(urls)) // Connections to close on exit
70
71 // Start a goroutine to for each URL to receive messages and send them to the messages channel.
72 // main() receives and prints them.
73 for _, urlStr := range urls {
74 debugf("Connecting to %s\n", urlStr)
75 go func(urlStr string) { // Start the goroutine
76 defer wait.Done() // Notify main() when this goroutine is done.
77 url, err := amqp.ParseURL(urlStr)
78 fatalIf(err)
79 c, err := container.Dial("tcp", url.Host) // NOTE: Dial takes just the Host part of the URL
80 fatalIf(err)
81 connections <- c // Save connection so we can Close() when main() ends
82 addr := strings.TrimPrefix(url.Path, "/")
83 opts := []electron.LinkOption{electron.Source(addr)}
84 if *prefetch > 0 { // Use a pre-fetch window
85 opts = append(opts, electron.Capacity(*prefetch), electron.Prefetch(true))
86 } else { // Grant credit for all expected messages at once
87 opts = append(opts, electron.Capacity(*count), electron.Prefetch(false))
88 }
89 r, err := c.Receiver(opts...)
90 fatalIf(err)
91 // Loop receiving messages and sending them to the main() goroutine
92 for {
93 if rm, err := r.Receive(); err == nil {
94 rm.Accept()
95 messages <- rm.Message
96 } else if err == electron.Closed {
97 return
98 } else {
99 log.Fatalf("receive error %v: %v", urlStr, err)
100 }
101 }
102 }(urlStr)
103 }
104
105 // All goroutines are started, we are receiving messages.
106 fmt.Printf("Listening on %d connections\n", len(urls))
107
108 // print each message until the count is exceeded.
109 for i := 0; i < *count; i++ {
110 m := <-messages
111 debugf("%v\n", m.Body())
112 }
113 fmt.Printf("Received %d messages\n", *count)
114
115 // Close all connections, this will interrupt goroutines blocked in Receiver.Receive()
116 // with electron.Closed.
117 for i := 0; i < len(urls); i++ {
118 c := <-connections
119 debugf("close %s", c)
120 c.Close(nil)
121 }
122 wait.Wait() // Wait for all goroutines to finish.
123 }
124
125 func fatalIf(err error) {
126 if err != nil {
127 log.Fatal(err)
128 }
129 }