Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 通过 Redis 实现 RPC 远程方法调用

我发现经常研究并且为之兴奋的一件事就是对系统进行扩展。现在这对不同的人有着不同的意思。作为移植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.htmRedis集群明细文档 http://www.linuxidc.com/Linux/2013-09/90118.htmUbuntu 12.10下安装Redis(图文详解)+ Jedis连接Redis http://www.linuxidc.com/Linux/2013-06/85816.htmRedis系列-安装部署维护篇 http://www.linuxidc.com/Linux/2012-12/75627.htmCentOS 6.3安装Redis http://www.linuxidc.com/Linux/2012-12/75314.htmRedis安装部署学习笔记 http://www.linuxidc.com/Linux/2014-07/104306.htmRedis配置文件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":fib1..30).each { |i| puts client.fib(i) }Serverrequire "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