学习札记———thrift在RubyOnRails工程实践实录

发布时间:2020-07-21 15:18:35 作者:JackSongBlack
来源:网络 阅读:362
关于thrift 使用虽然语法简单但是在实践中还是出了一些问题,主要问题存在于我对ruby语法的不了解,下面就是我的实践实录
../xml.thrift
\**
*namespace 是命令空间 但是关于ruby的空间视乎还是有些问题
**\
namespace ruby XmlThrift
namespace java com.shsz.young.thrift.proto
\**
* 类型结构体
**\
struct Xmltype{
1:string xml
}
\**
*意外处理数据结构体
**\
exception InvalidOperation {
    1: string errors
}
\**
*提供服务
**\
service XmlResponce{

string input(1:string xml)throws(1: InvalidOperation errors), \*throws 是指发生意外返回的情况
string output(1:string xml)throws(1: InvalidOperation errors),

oneway void push() \* oneway 是指单边处理

}
然后执行
thrift -r --gen rb xml.thrift
生成文件应该由一下三个

xml_constants.rb
xml_responce.rb
xml_types.rb

我主要卡壳在文件载入这个上面,经过google几番查找后终于寻得法子使用绝对路径,才能应付,脚本生成的代码在RubyOnRails工程中还需要修改下 ,主要是引用文件路径上。原教程在$..push('../ruby_gen')但是在工程中有各种问题,绝对路径代码如下

require File.expand_path('../../../gen-rb/xml_types', __FILE__)   

__FILE__ 这句话代表文件在工程的绝对路径

2.ruby端server实践代码

#encoding:utf-8
require 'thrift'
require File.expand_path('../../../gen-rb/xml_types', __FILE__)    \
require File.expand_path('../../../gen-rb/xml_responce', __FILE__)

class XmlServerHandler
    def initialize

    end

    def input(xml)
        puts xml
        'xml'
    end

    def output(xml)
     puts xml
        xml
    end

    def push()
        print "服务器已启动"
    end
end

def new_server
    handler = XmlServerHandler.new
    processor = XmlResponce::Processor.new(handler)
    transport = Thrift::ServerSocket.new(9090)
    transportFactory = Thrift::BufferedTransportFactory.new()
    server = Thrift::SimpleServer.new(processor, transport, transportFactory)

    puts "Starting the    server..."

    server.serve()
    puts "done."
end

3. ruby端client实践
#encoding:utf-8


require 'thrift'
require File.expand_path('../../../gen-rb/xml_types', __FILE__)
require File.expand_path('../../../gen-rb/xml_responce', __FILE__)


begin

    transport = Thrift::BufferedTransport.new(Thrift::Socket.new('localhost', 9090))
    protocol = Thrift::BinaryProtocol.new(transport)
    client = XmlResponce::Client.new(protocol)

    transport.open()


    # Run a remote calculation
    puts client.input('xml')    #it accessing the ruby server program method calc via thrift service

    puts client.output('xml')
    #Run a Async call
    client.push()

    transport.close()
rescue
    puts $!
end
这里比较突出的是begin  rescue end 语法,他的意思是 首先执行begin 包裹的代码,如果出现意外则执行rescue包裹的代码


另外 初次接触了ruby多线程编程

简单开辟新线程的方式是

thread =Thread.New() 括号里可包裹你要执行的方法
但是只是这样还是不行的,在ruby中,当主线程执行完后,会杀死所有子线程所有还需要用jion这个关键字来让主线程等待子线程执行完
 
thread .jion

推荐阅读:
  1. 我们都是IT民工---------流浪人IDE开发札记
  2. 学习札记——ruby的对象模型

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

thrift rubyonrails 工程实践

上一篇:opencv如何实现矩形检测

下一篇:git中ssh key配置的详细解析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》