当前位置:网站首页>Thrift getting started
Thrift getting started
2022-06-26 00:07:00 【Keyboard singer】
One 、 brief introduction
Thrift By the first FaceBook Research and development , It is mainly used for communication between various services RPC signal communication , Support for cross language , Common languages such as C++,Java,Python,PHP,Ruby,Erlang,Perl,Haskell,C# wait .
Thrift It's a typical CS( client / Server side ) structure , Client and server can be developed in different languages , Then there must be an intermediate language to associate the languages of the client and the server , This language is IDL(Interface Description Language)
Two 、 Front end environment configuration
I am using mac System , Need to be installed on your computer homebrew, In use homebrew To install git and thrift.git Your environment is installation thrift The basis of !
1.homebrew Installation :
xcode-select --install
/usr/bin/ruby -e "$(curl -fsSL https://cdn.jsdelivr.net/gh/ineo6/homebrew-install/install)"
2.git Installation
brew install git
3.thrift Installation :
brew install thrift
4. The identification of successful installation is as follows :
as for windows Installation , Details please see Official website
3、 ... and 、Thrift type
1. data type
Thrift Unsigned types are not supported
byte: Signed byte
i16:16 Bit signed integer
i32:32 Bit signed integer
i64:64 Bit signed integer
double:64 Bit floating point
string: character string
2. Container type
Elements in a collection can be anything other than service Any type other than , Include exception
list: A series of T An ordered list of types of data , Elements can be repeated
set: A series of T An unordered list of types of data , Element is not repeatable
map: A dictionary structure ,key by K type ,value by V type , amount to Java Medium HashMap
Four 、Thrift working principle
1、 How to realize the communication between multiple languages ?
Data transmission uses socket( Many languages support ), Data in a specific format (String etc. ) send out , The language of the receiver shall be parsed
2、 Definition thrift The file of , from thrift file (IDL) Generate interfaces for both languages 、model, In the generated model And there will be decoding code in the interface .
5、 ... and 、Demo Small cases
1. introduce maven rely on
<dependency>
<groupId>org.apache.thrift</groupId>
<artifactId>libthrift</artifactId>
<version>0.14.2</version>
</dependency>
2. To write thrift file
namespace java thrift.generated
typedef i16 short
typedef i32 int
typedef i64 long
typedef bool boolean
typedef string String
struct Person {
1: optional String username,
2: optional int age,
3: optional boolean married
}
exception DataException {
1: optional String message,
2: optional String callStack,
3: optional String date
}
service PersonService {
Person getPersonByUsername(1: required String username) throws (1: DataException dataException),
void savePerson(1: required Person person) throws (1: DataException dataException)
}
3. Generate for by command gen-java file


If the class file is red ! Please add package sentence :
4. To write Server End code
package com.maoyan.luzelong.thrift.test;
import com.maoyan.luzelong.thrift.generated.PersonService;
import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.layered.TFramedTransport;
public class ThriftServer {
public static void main(String[] args) throws Exception{
TNonblockingServerSocket socket = new TNonblockingServerSocket(8899);
THsHaServer.Args arg = new THsHaServer.Args(socket).minWorkerThreads(2).maxWorkerThreads(4);
PersonService.Processor<PersonServiceImpl> processor = new PersonService.Processor<>(new PersonServiceImpl());
arg.protocolFactory(new TCompactProtocol.Factory());
arg.transportFactory(new TFramedTransport.Factory());
arg.processorFactory(new TProcessorFactory(processor));
TServer server = new THsHaServer(arg);
System.out.println("Thrift Server start");
server.serve();
}
}
5. To write Client End
package com.maoyan.luzelong.thrift.test;
import com.maoyan.luzelong.thrift.generated.Person;
import com.maoyan.luzelong.thrift.generated.PersonService;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.layered.TFramedTransport;
public class ThriftClient {
public static void main(String[] args) throws TTransportException {
TTransport transport = new TFramedTransport(new TSocket("localhost",8899),600);
TProtocol protocol = new TCompactProtocol(transport);
PersonService.Client client = new PersonService.Client(protocol);
try{
transport.open();
Person person = client.getPersonByUsername(" Zhang San ");
System.out.println(person.getUsername());
System.out.println(person.getAge());
System.out.println(person.isMarried());
System.out.println("---------");
Person person2 = new Person();
person2.setUsername(" Li Si ");
person2.setAge(30);
person2.setMarried(true);
client.savePerson(person2);
}catch (Exception e){
throw new RuntimeException(e.getMessage(),e);
}finally {
transport.close();
}
}
}
6. test ( First run Server, Run again Client)

边栏推荐
- Static keyword explanation
- Smt贴片加工出现元件立碑的解决方法
- Let's talk about string today
- Rocket message storage
- 剑指 Offer 48. 最长不含重复字符的子字符串
- 别再吃各种维生素C片了,这6种维生素C含量最高的水果
- Oracle writes a trigger that inserts a piece of data first and updates a field in the data
- Alipay payment interface sandbox environment test and integration into an SSM e-commerce project
- 《网络是怎么样连接的》读书笔记 - 集线器、路由器和路由器(三)
- Redis之内存淘汰机制
猜你喜欢

How postman tests interfaces that require login

文献调研(二):基于短期能源预测的建筑节能性能定量评估

Thrift入门学习

博图软件中多重背景块的建立_过路老熊_新浪博客

WINCC与STEP7的仿真连接_过路老熊_新浪博客

Connecting MySQL database with VBScript_ Old bear passing by_ Sina blog

Lazy people teach you to use kiwi fruit to lose 16 kg in a month_ Old bear passing by_ Sina blog

6. common instructions (upper) v-cloak, v-once, v-pre

猕猴桃酵素的功效_过路老熊_新浪博客

Common problems encountered when creating and publishing packages using NPM
随机推荐
(转载)进程和线程的形象解释
用frp搭建云电脑
Rocket之消息存储
86.(cesium篇)cesium叠加面接收阴影效果(gltf模型)
10.2.3、Kylin_kylin的使用,维度必选
懒人教你用猕猴桃一月饱减16斤_过路老熊_新浪博客
Record some CF questions
[wechat official account H5] generates a QR code with parameters to enter the official account attention page to listen to user-defined menu bar for official account events (server)
Keil compilation run error, missing error: # 5: # includecore_ cm3.h_ Old bear passing by_ Sina blog
Circuit de fabrication manuelle d'un port série de niveau USB à TTL pour PL - 2303hx Old bear passing Sina blog
关于scrapy爬虫时,由spider文件将item传递到管道的方法注意事项
ValueError: color kwarg must have one color per data set. 9 data sets and 1 colors were provided解决
ASA如何配置端口映射及PAT
10.4.1 données intermédiaires
Literature research (IV): Hourly building power consumption prediction based on case-based reasoning, Ann and PCA
Stop eating vitamin C tablets. These six fruits have the highest vitamin C content
Final and static
postman如何测试需要登录的接口
huibian
Record a simple question with ideas at the moment of brushing leetcode - Sword finger offer 09 Implementing queues with two stacks