通過Redis實現RPC遠程方法調用
我發現經常研究并且為之興奮的一件事就是對系統進行擴展?,F在這對不同的人有著不同的意思。作為移植Monolithic應用到Microservices架構方法中的一部分,如何處理Microservices架構是我研究RPC的原因。
RPC(或者叫做遠程進程調用)是一個已經在計算機科學領域存在較長一段時間的概念。對此一種非常簡單的理解就是發送一段消息到遠程進程的能力,而不論它是在同一個系統上還是遠程的系統??偟膩碚f這是非常模糊的,而且對許多的實現來說是開放的。在我看來,當談到RPC時,會有相當多的內容可供探討,比如消息的格式,以及你怎樣將消息發送到遠程進程上。有許多的方法來實現RPC,而這是我采用的一種,但對這篇文章來說,我準備使用‘JSON-RPC’來處理消息的格式,用Redis來發布消息。
RPC和消息隊列
原理基本上都一樣,但是使用RPC的話,客戶端會等待一個含有RPC調用結果的返回消息。如果你的消息隊列系統允許你為發送者處理回調消息,那么你很可能就可以為RPC來使用它。在大多數的消息隊列中,它們被用來觸發那些不再需要回復給客戶端的任務。
為什么用Redis而不是其它的?
你應該能夠在某個地主發現Redis是非常先進的技術,如果你說沒有發現,你是怎么了?Redis對很多事情來說都是一個偉大的工具,你應該認真研究一下。學習之路能夠平坦,并且不用學習太多的新內容,Redis都完美的符合這些想法,所以,讓我們看看我們可以干些什么。
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有命令能夠讓你阻塞等待。這是非常優秀的做法,它讓你的客戶端代碼看上去像是在調用本地方法。
Ruby 相當酷,可是。。。
如果你想用其它語言怎么辦?沒問題,只要你的語言有很好的Redis庫,你就可以做同樣的事。讓我們瞧一瞧用Python來建立一個服務端程序。
- import redis
- import msgpack
- class Fibonacci:
- def fib(self,n):
- if n == 0:
- return 0
- elif n == 1:
- return 1
- else:
- return self.fib(n-1) + self.fib(n-2)
- class RedisRpcServer:
- def __init__(self, redis_url, list_name, klass):
- self.client = redis.from_url(redis_url)
- self.list_name = list_name
- self.klass = klass
- def start(self):
- print("Starting RPC server for " + self.list_name)
- while True:
- channel, request = self.client.brpop('fib')
- request = msgpack.unpackb(request, encoding='utf-8')
- print("Working on request: " + request['id'])
- result = getattr(self.klass, request['method'])(*request['params'])
- reply = {
- 'jsonrpc': '2.0',
- 'result': result,
- 'id': request['id']
- }
- self.client.rpush(request['id'], msgpack.packb(reply, use_bin_type=True))
- self.client.expire(request['id'], 30)
- RedisRpcServer('redis://localhost:6379', 'fib', Fibonacci()).start()
結論
這很好的證明了你頭腦中的一些想法,當然,還需要更多的工作來處理異常。如果你用這個方法遇到任何的問題,我樂意幫助你。我的確希望在同樣想法的一此地方使用RabbitMQ,但如果你已經在你的項目中使用了Redis,這將會是一個非常不錯的方法。
英文原文:RPC using Redis

























