[DRB]Distributed Ruby Objects Simple Sample

Distributed Ruby Objects (以下簡稱 drb),是 Ruby Standard Library 中用來做到類似 RPC (Remote procedure call) 的函式庫,以下紀錄最基本的 Server 端和 Client 端的 sample。

Server:

require ‘drb’

class TimeServer

def get_current_time
Time.now
end

def stop_server
DRb.stop_service
end

end

uri = ‘druby://localhost:7788’
front_object = TimeServer.new

DRb.start_service(uri, front_object)

# Wait for the drb server thread to finish before exiting.
DRb.thread.join

這樣一來最簡單的 Server 端就OK了,只要執行這段 Ruby code,Client端就可以用 druby://localhost:7788 來叫用服務。

Client:

require ‘drb’

server_uri = “druby://localhost:7788″

timeserver = DRbObject.new_with_uri(server_uri)

#call remote object method ‘get_current_time’
puts timeserver.get_current_time

#stop remote service
timeserver.stop_server

就這麼簡單,不過方便歸方便,安全的問題也要特別注意

若想深入了解的人可以參考以下連結:

Intro to DRb
drb: Ruby Standard Library Documentation

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s

%d 位部落客按了讚: