はじめに
この記事の続きになります。
今回は、前回作成した仕組みのクライアント側(SQLと結果を受け取る)を作成していきます。主な処理の流れは、Cloud Pub/SubにSQLを含んだメッセージを送信して、その結果が出力されているCloud Storageから結果を受け取ります。
クライアント側のコード
クライアントもRubyで書いていきます。Gemfileには次の2つのgemを追加します。
gem "google-cloud-pubsub"
gem "google-cloud-storage"
クライアント側のコードは次のようになります。
require "google/cloud/pubsub"
require "google/cloud/storage"
require "json"
require "securerandom"
def execute(query)
bucket_name = '{バケット名}'
topic_name = '{トピック名}'
pubsub = Google::Cloud::PubSub.new
topic = pubsub.topic(topic_name)
query_id = SecureRandom.hex(10)
publish_message = {
id: query_id,
query: query
}
message = topic.publish(JSON.generate(publish_message))
return nil unless query.downcase.index('select') == 0
storage = Google::Cloud::Storage.new
bucket = storage.bucket(bucket_name, skip_lookup: true)
filename = "output/#{query_id}.txt"
for i in 0..5
sleep(1)
file = bucket.file(filename)
unless file.nil?
download = file.download
download.rewind
json = download.read
return JSON.parse(json)
end
end
return nil
end
rows = execute('SELECT * FROM users;')
p(rows)
Pub/Subにメッセージを送った後に処理が完了するまで(ファイルが作成されているかどうか)待ち、作成されている場合にはダウンロードして結果を返しています。利用する時にはexecuteにSQLの文字列を引数として設定して呼び出すと結果を取得できるようにしています。
実行前にGoogle Cloudの認証情報の鍵を設定しておく必要があります。また、この鍵に関連したアカウントのロールには、Cloud StorageのロールとCloud Pub/Subのロールである「Pub/Sub パブリッシャー」と「Pub/Sub 閲覧者」を設定しておきます。
export PUBSUB_CREDENTIALS={パス}
export STORAGE_CREDENTIALS={パス}
実行する時は次のようにします。
ruby client.rb
取得した結果は、出力されるようになっていますので無事に実行できると表示されるかと思います。
おわりに
今回は、簡単な仕組みで試してみました。sleepの箇所などは確認の頻度を上げても良いのではないかと思います。