PubSubでメッセージを送付する[Ruby]


This article describes how to send message to PubSub on GCP.

🗻 Installation

Please modify your Gemfile and execute bundle install.

gem 'google-cloud-pubsub'

🚕 How to send

require 'securerandom'
require 'google/cloud/pubsub'

class PubSub
def send_message(params:)
return if !Rails.env.staging? && !Rails.env.production?

post_params = _generate_log_hash(params)
_topic.publish(post_params.to_json.to_s)
end

def send_multi_message(params_list:)
return if !Rails.env.staging? && !Rails.env.production?

_topic.publish do |batch|
params_list.each do |params|
post_params = _generate_log_hash(params)
batch.publish(post_params.to_json.to_s)
end
end
end

private def _topic
return @topic if @topic.present?

# On GCP
# pubsub = Google::Cloud::Pubsub.new

# For development
pubsub = Google::Cloud::Pubsub.new(
project: 'sample-project',
keyfile: './gcp-credencial-for-sample-project.json'
)

@topic = pubsub.topic('core')
end

private def _generate_log_hash(params)
{
event_time: Time.current.iso8601(6),
log_id: SecureRandom.uuid
}.merge(params)
end
end

pubsub = PubSub.new
pubsub.send_message('sample-message')

🎂 References

http://googleapis.github.io/google-cloud-ruby/docs/google-cloud-pubsub/latest/

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!