【Thrift/Vertx】关于Thrift和Vertx的服务整合
2017-11-26 22:05
281 查看
官网上都有关于Thrift的新手demo示例,本文主要讲解其中一项,就是怎么整合Thrift和Vertx。
Vertx是一种事件驱动的异步框架,需要JDK8支持,开发过程中很多都需要用到lambda表达式。vertx的简要介绍可以参考笔者之前的一篇文章:【Vertx】利用vertx实现websocket数据推送
本demo的前端代码地址:
Vertx是一种事件驱动的异步框架,需要JDK8支持,开发过程中很多都需要用到lambda表达式。vertx的简要介绍可以参考笔者之前的一篇文章:【Vertx】利用vertx实现websocket数据推送
1,首先定义thrift接口文件
定义thrift文件的规则请参看thrift官网,http://thrift.apache.org/static/files/thrift-20070401.pdf2,利用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
相关文章推荐
- 关于整合Nginx+Tomcat搭建高性能负载均衡服务体系
- 一个关于非结构化数据整合服务平台的好消息
- Apache Thrift - 可伸缩的跨语言服务开发框架(转发)不错
- spring与cxf整合开发webservice服务接口
- (二)整合spring cloud云服务架构 - particle云架构
- 记一次,关于思杰虚拟化XEN-API服务无法启动
- (11)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- Thrift高效通讯 (完结)
- 关于调用复杂的soa服务治理的一点思考
- 关于windows服务编程注意事项
- 关于dubbo创建服务和引用服务时,会报错:cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration...
- python部署thrift服务以及客户端
- 关于JSP发布地图服务(转)
- 第二章:Dubbo整合maven+spring+springmvc+mybatis之服务提供者搭建
- 关于spring4和hibernate4整合,配置事务报“Cannot unwrap to requested type [javax.sql.DataSource]”错误的解决方法及心得
- 整合阿里dubbo服务的项目搭建实战(springboot)
- 关于dubbo服务的xml配置文件报错的问题
- 关于一个服务上面多个应用的场景
- 关于使用SSM整合的时候,使用hibernate校验框架出现500异常问题解决
- Google即将整合Writely服务
- 关于thrift需要注意的地方