-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsubscriber-example.rb
More file actions
73 lines (62 loc) · 1.8 KB
/
Copy pathsubscriber-example.rb
File metadata and controls
73 lines (62 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
require "gcpc"
# Please execute commands below.
#
# ```
# $ gcloud beta emulators pubsub start
# $ bundle exec ruby examples/subscriber-example/subscriber-example.rb
# $ bundle exec ruby examples/publisher-example/publisher-example.rb
# ```
PROJECT_ID = "project-example-1"
TOPIC_NAME = "topic-example-1"
SUBSCRIPTION_NAME = "subscription-example-1"
MyLogger = Logger.new(STDOUT)
class LogInterceptor < Gcpc::Subscriber::BaseInterceptor
def handle(data, attributes, message)
MyLogger.info "[Interceptor Log] #{message.inspect}"
MyLogger.info "[Interceptor Log] data: #{data}"
MyLogger.info "[Interceptor Log] attributes: #{attributes}"
yield data, attributes, message
end
end
class LogHandler < Gcpc::Subscriber::BaseHandler
def handle(data, attributes, message)
MyLogger.info "[Handler Log] #{message.inspect}"
MyLogger.info "[Handler Log] data: #{data}"
MyLogger.info "[Handler Log] attributes: #{attributes}"
end
end
# We create topic and subscription only for demonstration.
def with_setup_subscription(&block)
project = Google::Cloud::Pubsub.new(
project_id: PROJECT_ID,
emulator_host: "localhost:8085",
)
if (topic = project.topic(TOPIC_NAME)).nil?
# Create a topic if necessary
topic = project.create_topic(TOPIC_NAME)
end
if (subscription = topic.subscription(SUBSCRIPTION_NAME)).nil?
# Create a subscription if necessary
subscription = topic.create_subscription(SUBSCRIPTION_NAME)
end
yield
ensure
topic.delete
subscription.delete
end
def run
subscriber = Gcpc::Subscriber.new(
project_id: PROJECT_ID,
subscription: SUBSCRIPTION_NAME,
interceptors: [LogInterceptor],
emulator_host: "localhost:8085",
)
subscriber.handle(LogHandler)
subscriber.run
end
def main
with_setup_subscription do
run
end
end
main