当前位置: 首页 > news >正文

Springboot整合Thrift

Springboot整合Thrift

编写thrift接口文件,并生成对应的服务端和客户端的代码

// 生成代码的文件路径
namespace java com.wdlm.thrift.code
namespace py py.com.wdlm.thrift.code// 将thrift数据类型标记为Java的数据类型
typedef i16 short
typedef i32 int
typedef i64 long
typedef string String
typedef bool boolean// 定义对象
struct Student{
1:optional String name,
2:optional int age,
3:optional String sex,
4:optional String address
}//定义数据异常
exception DataException{1:optional int code,2:optional String messsage,3:optional String dataTime
}// 定义服务
service StudentService{//通过名称获取学生信息Student getStudentByName(1:required String name) throws (1:DataException dataException),//保存学生信息void save(1:required Student student) throws (1:DataException dataException)
}
thrift --gen java student.thrift

服务端发布

创建一个maven的项目 thrift-server

在maven中添加对应的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.wdlm</groupId><artifactId>thrift-server</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.12</version> <!-- 使用 Spring Boot 2 的版本 --><relativePath/> <!-- lookup parent from repository --></parent><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.apache.thrift</groupId><artifactId>libthrift</artifactId><version>0.22.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies></project>

创建一个Service服务,实现StudentService.Iface接口

package com.wdlm.thrift.service;import com.wdlm.thrift.code.DataException;
import com.wdlm.thrift.code.Student;
import com.wdlm.thrift.code.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TException;
import org.springframework.stereotype.Service;@Service
@Slf4j
public class StudentServiceImpl implements StudentService.Iface {@Overridepublic Student getStudentByName(String name) throws DataException, TException{log.info("服务端收到客户端getStudentByName请求,name:" + name);//模拟数据Student student = new Student();student.setName("今天不coding");student.setAge(18);student.setSex("男");student.setAddress("北京");//模拟耗时try {Thread.sleep(5000);} catch (InterruptedException e) {throw new RuntimeException(e);}log.info("服务端返回数据给客户端getStudentByName请求,student" + student);return student;}@Overridepublic void save(Student student) throws DataException, TException {log.info("服务端收到客户端saveStudent请求,student:" + student);//模拟耗时try {Thread.sleep(5000);} catch (InterruptedException e) {throw new RuntimeException(e);}log.info("保存成功");}
}

配置服务端端口及线程池参数

server:thrift:port: 9001min-threads-pool: 100max-threads-pool: 1000

创建服务端对象

package com.wdlm.thrift.server;import com.wdlm.thrift.code.StudentService;
import com.wdlm.thrift.service.StudentServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.THsHaServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.layered.TFramedTransport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;@Slf4j
public class StudentServer {/*** 监听的端口*/@Value("${server.thrift.port}")private Integer port;/*** 线程池最小线程数*/@Value("${server.thrift.min-threads-pool}")private Integer minThreadPool;/*** 线程池最大线程数*/@Value("${server.thrift.max-threads-pool}")private Integer maxThreadPool;@Autowiredprivate StudentServiceImpl studentService;/*** 开启服务*/public void start() {try {// TNonblockingServerSocket: 非阻塞的socketTNonblockingServerSocket socket = new TNonblockingServerSocket(port);// THsHaServer:一个高可用的ServerTHsHaServer.Args args = new THsHaServer.Args(socket).minWorkerThreads(minThreadPool).maxWorkerThreads(maxThreadPool);// Processor:处理业务逻辑StudentService.Processor<StudentServiceImpl> processor = new StudentService.Processor<>(studentService);// 设置协议工厂, TCompactProtocol:二进制压缩协议args.protocolFactory(new TCompactProtocol.Factory());// 设置传输工厂, TFramedTransport:以frame为单位进行调用,非阻塞式服务args.transportFactory(new TFramedTransport.Factory());// 设置处理器工厂args.processorFactory(new TProcessorFactory(processor));// 创建半同步半异步的serverTHsHaServer server = new THsHaServer(args);// 启动serverserver.serve();log.info("thrift server has been started, port:" + port);} catch (TTransportException e) {e.printStackTrace();}}
}

启动类中添加Server的启动配置

package com.wdlm.thrift.server;import com.wdlm.thrift.server.server.StudentServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;@SpringBootApplication
public class ServerApplication {public static void main(String[] args) {SpringApplication.run(ServerApplication.class, args);}/*** 向spring注册bean对象* initMethod = "start" 表示启动时调用start方法* start方法执行后,服务端阻塞,等待接受客服端的请求*/@Beanpublic StudentServer studentServer(){StudentServer studentServer = new StudentServer();studentServer.start();return studentServer;}
}

调用端发布

创建一个maven项目 thrift-client

在maven中添加对应的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.wdlm</groupId><artifactId>thrift-client</artifactId><version>1.0-SNAPSHOT</version><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.12</version> <!-- 使用 Spring Boot 2 的版本 --><relativePath/> <!-- lookup parent from repository --></parent><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><dependency><groupId>org.apache.thrift</groupId><artifactId>libthrift</artifactId><version>0.22.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies></project>

配置远程服务端端口

server:port: 8001thrift:host: localhostport: 9001

创建客户端对象

package com.wdlm.thrift.client.client;import com.wdlm.thrift.client.code.StudentService;
import lombok.Setter;
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 StudentClient {/*** 主机*/@Setterprivate String host;/*** 端口*/@Setterprivate Integer port;/*** 传输层*/private TTransport transport;/*** 协议层*/private TProtocol protocol;private StudentService.Client client;/*** 初始化*/public void init() throws TTransportException {transport = new TFramedTransport(new TSocket(host, port), 600);protocol = new TCompactProtocol(transport);client = new StudentService.Client(protocol);}/*** 获取客服端对象*/public StudentService.Client getService(){return client;}/*** 打开连接*/public void open() throws TTransportException {if (null != transport && !transport.isOpen()){transport.open();}}/*** 关闭连接*/public void close() {if (null != transport && transport.isOpen()){transport.close();}}}

创建一个自动配置类,用于将客户端对象托管到spring容器

package com.wdlm.thrift.client.configuration;import com.wdlm.thrift.client.client.StudentClient;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.web.context.WebApplicationContext;@Configuration
public class StudentClientConfig {/*** 服务端主机*/@Value("${server.thrift.host}")private String host;/*** 服务端端口*/@Value("${server.thrift.port}")private Integer port;/*** 每次请求实例化一个新的客户端对象*/@Bean@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)public StudentClient studentClient() throws TTransportException {StudentClient studentClient = new StudentClient();studentClient.setHost(host);studentClient.setPort(port);studentClient.init();return studentClient;}
}

定义Service接口

package com.wdlm.thrift.client.service;import com.wdlm.thrift.client.code.Student;public interface StudentService {/*** 根据姓名获取学生信息* @param name* @return Student*/Student getStudentByName(String name);/*** 保存学生信息* @param student*/void save(Student student);}

实现Service接口

package com.wdlm.thrift.client.service.impl;import com.wdlm.thrift.client.client.StudentClient;
import com.wdlm.thrift.client.code.Student;
import com.wdlm.thrift.client.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
@Slf4j
public class StudentServiceImpl implements StudentService {@Autowiredprivate StudentClient studentClient;@Overridepublic Student getStudentByName(String name) {try {studentClient.open();log.info("客户端根据学生姓名查询学生信息,name:" + name);return studentClient.getService().getStudentByName(name);} catch (Exception e) {log.error("客户端根据学生姓名查询学生信息报错" + e);throw new RuntimeException(e);} finally {studentClient.close();}}@Overridepublic void save(Student student) {try {studentClient.open();log.info("客户端保存学生信息请求" + student);studentClient.getService().save(student);} catch (Exception e) {log.error("客户端保存学生信息请求报错" + e);throw new RuntimeException(e);} finally {studentClient.close();}}
}

创建controller

package com.wdlm.thrift.client.controller;import com.wdlm.thrift.client.code.Student;
import com.wdlm.thrift.client.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/student")
public class StudentController {@Autowiredprivate StudentService studentService;@GetMapping("/getStudentByName")public Student getStudentByName(String name) {return studentService.getStudentByName(name);}@PostMapping("/save")public Student save(@RequestBody Student student) {studentService.save(student);return student;}}
http://www.dtcms.com/a/328523.html

相关文章:

  • 移动端网页调试实战,键盘弹出与视口错位问题的定位与优化
  • 汉高携手SAP推出AI驱动的退换货与争议管理解决方案
  • 赛灵思ZYNQ官方文档UG585自学翻译笔记:UART Controller,通用异步收发传输器控制器
  • Vue接口平台十三——测试记录
  • Ubuntu 全盘备份
  • 九尾狐未来机械晶核技术
  • k3s部署
  • 电脑硬件详解
  • ZYNQ AXI-GPIO学习——ZYNQ学习笔记8
  • 学习游制作记录(背包UI以及各种物品的存储)8.12
  • kafka 消费者组的概念是什么?它是如何实现消息的点对点和发布/订阅模式?
  • Supabase快速入门与实战指南
  • LangChain 入门学习
  • Spring AI Alibaba - 聊天机器人快速上手
  • SpringAI 使用通义千问进行聊天对话开发
  • 考研复习-计算机组成原理-第五章-CPU
  • [NoC]Outstanding和Credit的概念详解
  • Fluent Bit 日志合并正则表达式(上)
  • Nginx 高级配置
  • Python训练Day41
  • 基于PAI-ChatLearn的GSPO强化学习实践
  • LLM - 搭建 Grounded SAM 2 模型的视觉检测与分割服务 API
  • CMake笔记:PUBLIC/PRIVATE/INTERFACE的使用
  • FreeRTOS---基础知识6---事件组
  • Effective C++ 条款37:绝不重新定义继承而来的缺省参数值
  • Linux系统编程Day13 -- 程序地址空间
  • Vue3 整合高德地图完成搜索、定位、选址功能,已封装为组件开箱即用(最新)
  • 前端对接豆包AI(vue3+TS版本)
  • 力扣-739.每日温度
  • Leetcode-138. 复制带随机指针的链表