歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 通過 Redis 實現 RPC 遠程方法調用

通過 Redis 實現 RPC 遠程方法調用

日期:2017/3/1 9:40:30   编辑:Linux編程

我發現經常研究並且為之興奮的一件事就是對系統進行擴展。現在這對不同的人有著不同的意思。作為移植Monolithic應用到Microservices架構方法中的一部分,如何處理Microservices架構是我研究RPC的原因。

RPC(或者叫做遠程進程調用)是一個已經在計算機科學領域存在較長一段時間的概念。對此一種非常簡單的理解就是發送一段消息到遠程進程的能力,而不論它是在同一個系統上還是遠程的系統。總的來說這是非常模糊的,而且對許多的實現來說是開放的。在我看來,當談到RPC時,會有相當多的內容可供探討,比如消息的格式,以及你怎樣將消息發送到遠程進程上。有許多的方法來實現RPC,而這是我采用的一種,但對這篇文章來說,我准備使用‘JSON-RPC’來處理消息的格式,用Redis來發布消息。

RPC和消息隊列

原理基本上都一樣,但是使用RPC的話,客戶端會等待一個含有RPC調用結果的返回消息。如果你的消息隊列系統允許你為發送者處理回調消息,那麼你很可能就可以為RPC來使用它。在大多數的消息隊列中,它們被用來觸發那些不再需要回復給客戶端的任務。

為什麼用Redis而不是其它的?

你應該能夠在某個地主發現Redis是非常先進的技術,如果你說沒有發現,你是怎麼了?Redis對很多事情來說都是一個偉大的工具,你應該認真研究一下。學習之路能夠平坦,並且不用學習太多的新內容,Redis都完美的符合這些想法,所以,讓我們看看我們可以干些什麼。

Ubuntu 14.04下Redis安裝及簡單測試 http://www.linuxidc.com/Linux/2014-05/101544.htm

Redis集群明細文檔 http://www.linuxidc.com/Linux/2013-09/90118.htm

Ubuntu 12.10下安裝Redis(圖文詳解)+ Jedis連接Redis http://www.linuxidc.com/Linux/2013-06/85816.htm

Redis系列-安裝部署維護篇 http://www.linuxidc.com/Linux/2012-12/75627.htm

CentOS 6.3安裝Redis http://www.linuxidc.com/Linux/2012-12/75314.htm

Redis安裝部署學習筆記 http://www.linuxidc.com/Linux/2014-07/104306.htm

Redis配置文件redis.conf 詳解 http://www.linuxidc.com/Linux/2013-11/92524.htm

Code

Client

require 'redis' require 'securerandom' require 'msgpack' class RedisRpcClient def initialize(redis_url, list_name) @client = Redis.connect(url: redis_url) @list_name = list_name.to_s end def method_missing(name, *args) request = { 'jsonrpc' => '2.0', 'method' => name, 'params' => args, 'id' => SecureRandom.uuid } @client.lpush(@list_name, request.to_msgpack) channel, response = @client.brpop(request['id'], timeout=30) MessagePack.unpack(response)['result'] end end client = RedisRpcClient.new('redis://localhost:6379', :fib) (1..30).each { |i| puts client.fib(i) }

Server

require 'redis' require 'msgpack' class Fibonacci def fib(n) case n when 0 then 0 when 1 then 1 else fib(n - 1) + fib(n - 2) end end end class RedisRpcServer def initialize(redis_url, list_name, klass) @client = Redis.connect(url: redis_url) @list_name = list_name.to_s @klass = klass end def start puts "Starting RPC server for #{@list_name}" while true channel, request = @client.brpop(@list_name) request = MessagePack.unpack(request) puts "Working on request: #{request['id']}" args = request['params'].unshift(request['method']) result = @klass.send *args reply = { 'jsonrpc' => '2.0', 'result' => result, 'id' => request['id'] } @client.rpush(request['id'], MessagePack.pack(reply)) @client.expire(request['id'], 30) end end end RedisRpcServer.new('redis://localhost:6379', :fib, Fibonacci.new).start

確是如此,它能工作是因為當你等待數據從服務器傳回來時,Redis有命令能夠讓你阻塞等待。這是非常優秀的做法,它讓你的客戶端代碼看上去像是在調用本地方法。

更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2014-09/106068p2.htm

Copyright © Linux教程網 All Rights Reserved