【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文件都是自动生成的,需要将其他文件拷贝到同一目录下

<!--
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-->
<!--
  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements. See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership. The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing,
  software distributed under the License is distributed on an
  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  KIND, either express or implied. See the License for the
  specific language governing permissions and limitations
  under the License.
-->
<!--
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Thrift Javascript Bindings - Tutorial Example</title>

  <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">
  //<![CDATA[
  $(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($("<option></option>").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 Bindings</h2>
  <form action="">
  <table class="calculator">
    <tr>
      <td>num1</td>
      <td><input type="text" id="num1" value="20" onkeyup="javascript:auto_calc();"/></td>
    </tr>
    <tr>
      <td>Operation</td>
      <td><select id="op" size="1" onchange="javascript:auto_calc();"><option></option></select></td>
    </tr>
    <tr>
      <td>num2</td>
      <td><input type="text" id="num2" value="5" onkeyup="javascript:auto_calc();"/></td></tr>
    <tr>
      <td>result</td>
      <td><input type="text" id="result" value=""/></td></tr>
    <tr>
      <td><input type="checkbox" id="autoupdate" checked="checked"/>autoupdate</td>
      <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.thrift</a> 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值