【Thrift/Vertx】关于Thrift和Vertx的服务整合

官网上都有关于Thrift的新手demo示例,本文主要讲解其中一项,就是怎么整合Thrift和Vertx。

Vertx是一种事件驱动的异步框架,需要JDK8支持,开发过程中很多都需要用到lambda表达式。vertx的简要介绍可以参考笔者之前的一篇文章:【Vertx】利用vertx实现websocket数据推送

1,首先定义thrift接口文件

定义thrift文件的规则请参看thrift官网,http://thrift.apache.org/static/files/thrift-20070401.pdf

2,利用thrift的编译程序编译thrift文件

这一操作会生成一系列的java类,这些java类都是服务定义中需要使用到的类,例如本例中的shared和tutorial这两个package下的类(除了tutorial下的CalculatorHandler类)

3,实现服务接口

例如本例中的CalculatorHandler类,里面具体实现了加减乘除。

4,vertx实现http请求处理部分

下面是vertx和thrift整合中的关键代码

import javax.naming.spi.DirStateFactory.Result;

import org.apache.http.impl.client.FutureRequestExecutionMetrics;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TMemoryBuffer;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.CorsHandler;
import tutorial.Calculator;
import tutorial.CalculatorHandler;

public class VertxThriftTest extends AbstractVerticle{
    public static void main(String[] args) {
        Vertx vertx=Vertx.vertx();
        Router router = Router.router(vertx);
        //类::方法示例
//      vertx.createHttpServer().requestHandler(resquest->{
//          router.accept(resquest);
//      });
        // 解决跨域问题
        router.route().handler(
                CorsHandler.create("*").allowedMethod(HttpMethod.GET)
                        .allowedMethod(HttpMethod.POST)
                        .allowedMethod(HttpMethod.OPTIONS)
                        .allowedHeader("X-PINGARUNER")
                        .allowedHeader("Content-Type"));
        router.route("/server/*").handler(context->{
            context.request().handler(buffer->{
                byte[] arr=buffer.getBytes();
                vertx.executeBlocking(future->{
                    String result=thriftRequest(arr);
                    future.complete(result);
                }, res->{
                    if(res.succeeded()) {
                        context.response().end(res.result().toString());
                    }else {
                        context.response().end(res.cause().getMessage());
                    }
                });
            });
        });
        vertx.createHttpServer().requestHandler(router::accept).listen(8088, res->{
            if(res.succeeded()) {
                System.out.println("Server starts successfully!");
            }else {
                System.out.println("Server fails to start!");
            }
        });
        vertx.deployVerticle(new VertxThriftTest());
    }
    //将request请求的数据利用thrift定义的操作进行相应的处理(这里参数为二进制,因此需要进行前端请求数据的序列化)
    private static String thriftRequest(byte[] input){
        try{

            //Input
            TMemoryBuffer inbuffer = new TMemoryBuffer(input.length);           
            inbuffer.write(input);              
            TProtocol  inprotocol   = new TJSONProtocol(inbuffer);                   

            //Output
            TMemoryBuffer outbuffer = new TMemoryBuffer(100);           
            TProtocol outprotocol   = new TJSONProtocol(outbuffer);

            TProcessor processor = new Calculator.Processor(new CalculatorHandler());      
            processor.process(inprotocol, outprotocol);

            byte[] output = new byte[outbuffer.length()];
            outbuffer.readAll(output, 0, output.length);

            return new String(output,"UTF-8");
        }catch(Throwable t){
            return "Error:"+t.getMessage();
        }       
    }
}

5,实现前端

其他js文件都是自动生成的,需要将其他文件拷贝到同一目录下





<html lang="zh-CN">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Thrift Javascript Bindings - Tutorial Exampletitle>

  <script src="thrift.js"  type="text/javascript">script>
  <script src="tutorial_types.js"    type="text/javascript">script>
  <script src="shared_types.js"      type="text/javascript">script>
  <script src="SharedService.js"     type="text/javascript">script>
  <script src="Calculator.js"        type="text/javascript">script>

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">script>


  <script type="text/javascript" charset="utf-8">
  //
  $(document).ready(function(){
    // remove pseudo child required for valid xhtml strict
    $("#op").children().remove();
    // add operations to it's dropdown menu
    $.each(Operation, function(key, value) {
      $('#op').append($("").attr("value",value).text(key));
    });

     $('table.calculator').attr('width', 500);
  });

  function calc() {
    //var transport = new Thrift.Transport("http://127.0.0.1:9090");
    //var transport = new Thrift.Transport("http://127.0.0.1:8088/service");
    var transport = new Thrift.Transport("http://127.0.0.1:8088/server/thrift/transmit");
    var protocol  = new Thrift.Protocol(transport);
    var client    = new CalculatorClient(protocol);

    var work = new Work();
    work.num1 = $("#num1").val();
    work.num2 = $("#num2").val();
    work.op = $("#op").val();

    try {
        console.log("oook");
      result = client.calculate(1, work);
      console.log(result);
      $('#result').val(result);
      $('#result').css('color', 'black');
    } catch(ouch){
      $('#result').val(ouch.why);
      $('#result').css('color', 'red');
    }
  }

  function auto_calc() {
    if ($('#autoupdate:checked').val() !== undefined) {
      calc();
    }
  }
  //]]>
  script>

head>
<body>
  <h2>Thrift Javascript Bindingsh2>
  <form action="">
  <table class="calculator">
    <tr>
      <td>num1td>
      <td><input type="text" id="num1" value="20" onkeyup="javascript:auto_calc();"/>td>
    tr>
    <tr>
      <td>Operationtd>
      <td><select id="op" size="1" onchange="javascript:auto_calc();"><option>option>select>td>
    tr>
    <tr>
      <td>num2td>
      <td><input type="text" id="num2" value="5" onkeyup="javascript:auto_calc();"/>td>tr>
    <tr>
      <td>resulttd>
      <td><input type="text" id="result" value=""/>td>tr>
    <tr>
      <td><input type="checkbox" id="autoupdate" checked="checked"/>autoupdatetd>
      <td><input type="button" id="calculate" value="calculate" onclick="javascript:calc();"/>td>
    tr>
  table>
  form>

  <p>This Java Script example uses <a href="https://git-wip-us.apache.org/repos/asf?p=thrift.git;a=blob;f=tutorial/tutorial.thrift;hb=HEAD">tutorial.thrifta> and a Thrift server using JSON protocol and HTTP transport.
  p>
    <p>
        <a href="http://validator.w3.org/check/referer"><img
            src="http://www.w3.org/Icons/valid-xhtml10"
            alt="Valid XHTML 1.0!" height="31" width="88" />a>
    p>
body>
html>

本demo的前端代码地址:

Thrift前端demo

Thrift服务端demo

你可能感兴趣的:(Vertx,Thrift)