thrift学习笔记
Thrift学习笔记
一:thrift介绍

二 thrift数据传输协议
三 thrift传输层
四 thrift服务器端
五 thrift客户端
六 thrift开发步骤
1服务器端
2客户端
七 thrift数据类型
1基本类型
bool:布尔值,true 或 false
byte:8 位有符号整数
i16:16 位有符号整数
i32:32 位有符号整数
i64:64 位有符号整数
double:64 位浮点数
string:utf-8编码的字符串
2结构体类型
struct:定义公共的对象
enum: 枚举类型
3容器类型
list:对应 Java 的 ArrayList
set:对应 Java 的 HashSet
map:对应 Java 的 HashMap
4异常类型
exception:对应 Java 的 Exception
5服务类型
service:对应服务的类 提供接口
八 thrift例子
enum 类型
struct Student{
1: required i32 id
2: required string username
3: required string password
4: requried string number
5: optional double age
}
struct 类型
struct School{
1: required i32 id
2: required string name
3: required set<Student> students
4: required list<Student> rank
5: required map<string, string> number_name
}
service 类型
service ThriftMysqlService{
void addUser(1:Student user)
list<Student> queryAllUser()
Student queryOneUser(1:i32 id)
map<string, string> queryOneArticle(1:i32 id)
}
具体代码
thrift.thrift 定义数据类型和接口的文件
namespace java org.seava.thrift_example.thrift
struct User{
1: required i32 userId
2: required string username
3: required string password
}
service ThriftService{
void addUser(1:User user)
User queryUser(1:i32 id)
list<User> queryUserList()
map<string, string> queryUserNamePass()
map<i32, User> queryUserMap()
}
到apache的官网下载thrift.exe程序, 下载地址 http://thrift.apache.org/ ,下下来通过cmd命令窗口去运行如下命令
thrift -gen java xxx.thrift
接口实现 ThriftServiceImpl.java
package org.seava.thrift_example.thrift; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; public class ThriftServiceImpl implements ThriftService.Iface { public void addUser(User user) throws org.apache.thrift.TException{
System.out.println(user.userId + " " + user.username + " " + user.password);
} public User queryUser(int id) throws org.apache.thrift.TException{
System.out.println(id);
User user = new User();
user.userId = 100;
user.username = "FFF";
user.password = "NNN";
return user;
} public List<User> queryUserList() throws org.apache.thrift.TException{
User user = new User();
user.userId = 100;
user.username = "FFF";
user.password = "NNN";
User user2 = new User();
user2.userId = 102;
user2.username = "FFF2";
user2.password = "NNN2";
List<User> list = new ArrayList<User>();
list.add(user2);
list.add(user);
return list;
} public Map<String,String> queryUserNamePass() throws org.apache.thrift.TException{
User user = new User();
user.userId = 100;
user.username = "FFF";
user.password = "NNN";
Map<String, String> map = new HashMap<String, String>();
map.put("password", user.password);
map.put("useranme", user.username);
return map;
} public Map<Integer,User> queryUserMap() throws org.apache.thrift.TException{
User user = new User();
user.userId = 100;
user.username = "FFF";
user.password = "NNN";
User user2 = new User();
user2.userId = 102;
user2.username = "FFF2";
user2.password = "NNN2";
Map<Integer, User> map = new HashMap<Integer, User>();
map.put(user.userId, user);
map.put(user2.userId, user2);
return map;
} }
服务器 Server.java
package org.seava.thrift_example.thrift; import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TNonblockingServerTransport;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException; public class Server { public static int port = 8090; /**
* 简单服务器类型 阻塞单线程
* 步骤
* 创建TProcessor
* 创建TServerTransport
* 创建TProtocol
* 创建TServer
* 启动Server
*/
public static void startSimpleServer(){
//创建processor
TProcessor tprocessor = new ThriftService.Processor<ThriftService.Iface>(new ThriftServiceImpl());
try {
//创建transport 阻塞通信
TServerSocket serverTransport = new TServerSocket(port);
//创建protocol
TBinaryProtocol.Factory protocol = new TBinaryProtocol.Factory();
//将processor transport protocol设入到服务器server中
TServer.Args args = new TServer.Args(serverTransport);
args.processor(tprocessor);
args.protocolFactory(protocol);
//定义服务器类型 设定参数
TServer server = new TSimpleServer(args);
//开启服务
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
} /**
* 多线程服务器 阻塞多线程
*/
public static void startThreadPoolServer(){
//创建processor
TProcessor tprocessor = new ThriftService.Processor<ThriftService.Iface>(new ThriftServiceImpl());
try{
//创建transport 阻塞通信
TServerSocket serverTransport = new TServerSocket(port);
//创建protocol 数据传输协议
TBinaryProtocol.Factory protocol = new TBinaryProtocol.Factory();
TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverTransport);
args.processor(tprocessor);
args.protocolFactory(protocol);
//创建服务器类型 多线程
TServer server = new TThreadPoolServer(args);
//开启服务
server.serve();
}catch(Exception e){
e.printStackTrace();
}
} /**
* 非阻塞I/O
*/
public static void startTNonblockingServer(){
//创建processor
TProcessor tprocessor = new ThriftService.Processor<ThriftService.Iface>(new ThriftServiceImpl());
try{
//创建transport 非阻塞 nonblocking
TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(port);
//创建protocol 数据传输协议
TCompactProtocol.Factory protocol = new TCompactProtocol.Factory();
//创建transport 数据传输方式 非阻塞需要用这种方式传输
TFramedTransport.Factory transport = new TFramedTransport.Factory();
TNonblockingServer.Args args = new TNonblockingServer.Args(serverTransport);
args.processor(tprocessor);
args.transportFactory(transport);
args.protocolFactory(protocol);
//创建服务器 类型是非阻塞
TServer server = new TNonblockingServer(args);
//开启服务
server.serve();
}catch(Exception e){
e.printStackTrace();
}
} /**
* 半同步半异步的非阻塞I/O
*/
public static void startTHsHaServer(){
//创建processor
TProcessor tprocessor = new ThriftService.Processor<ThriftService.Iface>(new ThriftServiceImpl());
try{
//创建transport 非阻塞
TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(port);
//非阻塞需要的传输方式
TFramedTransport.Factory transport = new TFramedTransport.Factory();
//数据传输协议
TCompactProtocol.Factory protocol = new TCompactProtocol.Factory();
//创建半同步半异步服务
THsHaServer.Args args = new THsHaServer.Args(serverTransport);
args.processor(tprocessor);
args.transportFactory(transport);
args.protocolFactory(protocol);
//创建 服务类型
TServer server = new THsHaServer(args);
//开启服务
server.serve();
}catch(Exception e){
e.printStackTrace();
}
} public static void main(String args[]){
//开启简单服务器
// Server.startSimpleServer();
//开启多线程服务器
// Server.startThreadPoolServer();
// Server.startTNonblockingServer();
// Server.startTHsHaServer();
Server.startTNonblockingServer();
}
}
Server.java实现了简单服务器(阻塞单线程) 阻塞多线程 非阻塞 半同步半异步非阻塞
注意: 非阻塞时传输层需要选择TFramedTransport
客户端 Client.java
package org.seava.thrift_example.thrift; import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import org.apache.thrift.async.TAsyncClientManager;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.protocol.TProtocolFactory;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingSocket;
import org.apache.thrift.transport.TNonblockingTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport; public class Client implements Runnable { public static String ip = "localhost";
public static int port = 8090;
public static int time_out = 30000; /**
* 客户端设置
* 创建Transport
* 创建TProtocol
* 基于TTransport和TProtocol创建Client
* 调用Client的相应方法
*/
public static void startSimpleClient(){
TTransport transport = null;
try{
//创建Transport
transport = new TSocket(ip, port, time_out);
//创建TProtocol
TProtocol protocol = new TBinaryProtocol(transport);
//基于TTransport和TProtocol创建Client
ThriftService.Client client = new ThriftService.Client(protocol);
transport.open();
//调用client方法
List<User> list = client.queryUserList();
for(User user : list){
System.out.println(user.userId + " " + user.username + " " + user.password);
}
Map<String, String> map = client.queryUserNamePass();
System.out.println(map);
User user = client.queryUser(10);
System.out.println(user.userId + " " + user.username + " " + user.password);
Map<Integer, User> map_u = client.queryUserMap();
System.out.println(map_u);
User uu = new User();
uu.userId = 1111;
uu.username = "mmbbmmbb";
uu.password = "ppbbppbb";
client.addUser(uu);
}catch(Exception e){
e.printStackTrace();
}
} /**
* 调用阻塞服务器的客户端
*/
public static void startNonblockingClient(){
TTransport transport = null;
try{
transport = new TFramedTransport(new TSocket(ip, port));
TCompactProtocol protocol = new TCompactProtocol(transport);
ThriftService.Client client = new ThriftService.Client(protocol);
transport.open();
//调用client方法
List<User> list = client.queryUserList();
for(User user : list){
System.out.println(user.userId + " " + user.username + " " + user.password);
}
Map<String, String> map = client.queryUserNamePass();
System.out.println(map);
User user = client.queryUser(10);
System.out.println(user.userId + " " + user.username + " " + user.password);
Map<Integer, User> map_u = client.queryUserMap();
System.out.println(map_u);
User uu = new User();
uu.userId = 1111;
uu.username = "mmbbmmbb";
uu.password = "ppbbppbb";
client.addUser(uu);
}catch(Exception e){
e.printStackTrace();
}
} public static void startAsynClient(){
try{
TAsyncClientManager clientManager = new TAsyncClientManager();
TNonblockingTransport transport = new TNonblockingSocket(ip, port, time_out);
TProtocolFactory tprotocol = new TCompactProtocol.Factory();
ThriftService.AsyncClient asyncClient = new ThriftService.AsyncClient(tprotocol, clientManager, transport);
System.out.println("Client start ...");
CountDownLatch latch = new CountDownLatch(1);
AsynCallback callBack = new AsynCallback(latch);
System.out.println("call method queryUser start ...");
asyncClient.queryUser(100, callBack);
System.out.println("call method queryUser end");
boolean wait = latch.await(30, TimeUnit.SECONDS);
System.out.println("latch.await =:" + wait);
}catch(Exception e){
e.printStackTrace();
}
} public void run(){
Client.startSimpleClient();
} public static void main(String args[]){
//调用简单服务器
// Client.startSimpleClient();
/*Client c1 = new Client();
Client c2 = new Client(); new Thread(c1).start();
new Thread(c2).start();*/ // Client.startNonblockingClient();
// Client.startNonblockingClient();
Client.startAsynClient();
}
}
客户端实现了 阻塞单线程 和 异步客户端
具体代码在github上:https://github.com/WaterHsu/thrift-example.git
thrift学习笔记的更多相关文章
- Thrift学习笔记—IDL基本类型
thrift 采用IDL(Interface Definition Language)来定义通用的服务接口,并通过生成不同的语言代理实现来达到跨语言.平台的功能.在thrift的IDL中可以定义以下一 ...
- 学习笔记:The Log(我所读过的最好的一篇分布式技术文章)
前言 这是一篇学习笔记. 学习的材料来自Jay Kreps的一篇讲Log的博文. 原文很长,但是我坚持看完了,收获颇多,也深深为Jay哥的技术能力.架构能力和对于分布式系统的理解之深刻所折服.同时也因 ...
- springmvc学习笔记--Interceptor机制和实践
前言: Spring的AOP理念, 以及j2ee中责任链(过滤器链)的设计模式, 确实深入人心, 处处可以看到它的身影. 这次借项目空闲, 来总结一下SpringMVC的Interceptor机制, ...
- 学习笔记:The Log(我所读过的最好的一篇分布式技术文章)
前言 这是一篇学习笔记. 学习的材料来自Jay Kreps的一篇讲Log的博文. 原文非常长.可是我坚持看完了,收获颇多,也深深为Jay哥的技术能力.架构能力和对于分布式系统的理解之深刻所折服.同一时 ...
- Dubbo -- 系统学习 笔记 -- 依赖
Dubbo -- 系统学习 笔记 -- 目录 依赖 必需依赖 缺省依赖 可选依赖 依赖 必需依赖 JDK1.5+ 理论上Dubbo可以只依赖JDK,不依赖于任何三方库运行,只需配置使用JDK相关实现策 ...
- spring cloud 学习(二)关于 Eureka 的学习笔记
关于 Eureka 的学习笔记 个人博客地址 : https://zggdczfr.cn/ ,欢迎光临~ 前言 Eureka是Netflix开发的服务发现组件,本身是一个基于REST的服务.Sprin ...
- SparkSQL学习笔记
概述 冠状病毒来临,宅在家中给国家做贡献之际,写一篇随笔记录SparkSQL的学习笔记,目的有二,一是记录整理之前的知识作为备忘录,二是分享技术,大家共同进步,有问题也希望大家不吝赐教.总体而言,大数 ...
- js学习笔记:webpack基础入门(一)
之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...
- PHP-自定义模板-学习笔记
1. 开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2. 整体架构图 ...
随机推荐
- storm入门教程 第一章 前言[转]
1.1 实时流计算 互联网从诞生的第一时间起,对世界的最大的改变就是让信息能够实时交互,从而大大加速了各个环节的效率.正因为大家对信息实时响应.实时交互的需求,软件行业除了个人操作系统之外,数据库 ...
- hdu 2087-剪花布条(KMP)
题意: 求文本串最多可以分成几个模式串. 分析: KMP #include <map> #include <set> #include <list> #includ ...
- 2016计蒜之道复赛 百度地图的实时路况 floyd+cdq分治
链接:https://nanti.jisuanke.com/t/11217 奉上官方题解: 枚举 d(x , y , z) 中的 y,把 y 从这个图中删去,再求这时的全源最短路即可,使用 Floyd ...
- bjfu1164 Parity Game
简单规律题.首先想到的是,若01串中1有n个,则可以通过操作,使串中1的个数变为n-1.n-2……1.0个:第2个想到的是,如果n为奇数,可以通过操作,使串中1的个数最多变为n+1,而若n为偶数,则无 ...
- NiuTrans 日记 1
这些天把东北大学自然语言实验室的NiuTrans 系统搭建并按照例子将短语系统运行了一遍,写这个日记主要是为了以后能提醒自己在这其中遇到的问题. 环境:短语系统我是windows和linux都运行了, ...
- iOS多线程之GCD小记
iOS多线程之GCD小记 iOS多线程方案简介 从各种资料中了解到,iOS中目前有4套多线程的方案,分别是下列4中: 1.Pthreads 这是一套可以在很多操作系统上通用的多线程API,是基于C语言 ...
- DOM笔记(一):HTMLDocument接口
操作HTML文档的第一步就是获取对文档元素的引用,每一个元素在DOM中就是一个节点,所有的元素在DOM中构成一个节点树. 用于获取元素节点定义的方法定义于HTMLDocument接口,window.d ...
- hadoop-1.1.2集群搭建
Hadoop安装分为三种不同模式: 本地模式:hadoop在运行时,不使用hdfs,而是使用linux操作系统的文件系统.(默认hadoop就是本地模式) 伪分布模式:在一个节点上运行hadoop(指 ...
- 【hbase】使用thrift with python 访问HBase
HBase 版本: 0.98.6 thrift 版本: 0.9.0 使用 thrift client with python 连接 HBase 报错: Traceback (most recent ...
- TCL/Expect交互式自动化测试概要 - - ITeye技术网站
TCL/Expect交互式自动化测试概要 - - ITeye技术网站 expect是一种基于TCL,能与交互式程序进行"可程序化"会话的脚本语言,是一种可以提供"分支和嵌 ...