spring boot项目集成thrift事件交互

一、前言

上一篇文章对thrift进行说明,同时搭建了简单的Java项目对thrift服务端,客户端的项目搭建。但是如何集成到spring boot项目中?这将是本篇文章的主要课题,不多说了。直接上代码

二、项目构建

  • 2.1 pom文件

    org.apache.thrift
    libthrift
    0.12.0


   org.projectlombok
   lombok
   1.18.8
   true

  • 2.2 引入thirft生成的java文件
#由于生成的文件较大,不展示进行简单说明
ConnectionInfo :根据thrift语言自定义的对象
HelloService:此文件为主要文件,包含我们需要实现的接口Iface
  • 2.3 搭建Thrift服务
package cn.bintools.daios.example.thrift.server;

import cn.bintools.daios.example.thrift.HelloService;
import cn.bintools.daios.example.thrift.impl.HelloServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.thrift.TProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.TTransportFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 初始化thrift服务
 *
 * @author yunzhe
 * @version 1.0.0 2019-07-02-下午7:10
 */
@Component
@Slf4j
public class ThriftServer {
    @Value("${thrift.port}")
    private int port;

    private TBinaryProtocol.Factory protocolFactory;

    private TTransportFactory transportFactory;



    public void init(){
        protocolFactory = new TBinaryProtocol.Factory();
        transportFactory = new TTransportFactory();
    }

    public void start(){
        // HelloService.Processor processor = new HelloService.Processor(new HelloRpcController());
        TProcessor processor = new HelloService.Processor(new HelloServiceImpl());
        init();
        try {
            TServerTransport transport = new TServerSocket(port);
            //TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(transport);
            TServer.Args tArgs = new TServer.Args(transport);
            tArgs.processor(processor);
            tArgs.protocolFactory(protocolFactory);
            tArgs.transportFactory(transportFactory);
            /*tArgs.minWorkerThreads(minThreads);
            tArgs.maxWorkerThreads(macThreads);*/
            //多线程 在关闭时多次请求报null异常
            //TServer server = new TThreadPoolServer(tArgs);
            TServer server = new TSimpleServer(tArgs);
            log.info("thrift server start success, port={}",port);
            server.serve();
        } catch (TTransportException e) {
            log.error("thrift server start fail",e);
        }
    }
}    
  • 2.4 实现Thrift的Iface接口
package cn.bintools.daios.example.thrift.impl;
import cn.bintools.daios.example.thrift.ConnectionInfo;
import cn.bintools.daios.example.thrift.HelloService;
import org.apache.thrift.TException;

/**
 * 服务端实现
 *
 * @author yunzhe
 * @version 1.0.0 2019-07-02-下午7:14
 */
public class HelloServiceImpl implements HelloService.Iface {
    @Override
    public int add(int num1, int num2) throws TException {
        return num1+num2;
    }
    @Override
    public ConnectionInfo getConnInfoById(int cpId) throws TException {
        ConnectionInfo connectionInfo = new ConnectionInfo();
        connectionInfo.setConnId(12);
        connectionInfo.setConnectionName("ThrfaceiftConnName");
        connectionInfo.setUrl("192.168.1.162");
        connectionInfo.setPort(3306);
        connectionInfo.setUserName("mysql_conn");
        connectionInfo.setPassword("abc*&ABC123");
        return connectionInfo;
    }
}
  • 2.5 启动类
    项目启动时,需要将thrift服务也启动。暴露thrift的端口。具体修改如下
package cn.bintools.daios.example.thrift;

import cn.bintools.daios.example.thrift.server.ThriftServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class DemoApplication {
    private static ThriftServer thriftServer;
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
        try {
            thriftServer = context.getBean(ThriftServer.class);
            thriftServer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 2.6 客户端
package cn.bintools.daios.example.thrift.client;

import cn.bintools.daios.example.thrift.HelloService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
/**
 * 客户端
 *
 * @author yunzhe
 * @version 1.0.0 2019-07-02-下午7:15
 */
public class HelloServiceClient {
    public static void main(String[] args) {
        try {
            TTransport tTransport = new TSocket("127.0.0.1", 9899);
            tTransport.open();
            TProtocol protocol = new TBinaryProtocol(tTransport);
            HelloService.Client client = new HelloService.Client(protocol);
            System.out.println(client.add(200,200));
            System.out.println("连接名称"+client.getConnInfoById(12));
            tTransport.close();
        } catch (TTransportException e) {
            e.printStackTrace();
        }catch (TException e){
            e.fillInStackTrace();
        }
    }
}  

三、结果展示

  • 3.1 服务启动


    thirftServerResult.jpg

    从日志中可以明确看到thrift服务已经启动并开启的端口是9899

  • 3.2 客户端访问结果
    clientResult.jpg

    从客户端结果日志中可知:分别返回类impl类中的结果。同时是我们期望的结果信息。
    码云地址:https://gitee.com/huangjian163/springboot_thrift.git

四、jar项目转war项目

通过以上处理,我们已经将thrift集成到springboot项目中,并得到我们预期的结果。但是以上是spring boot的jar项目,如果改成war包是否能得到我们想要的结果?如何将spring boot 的jar转war可参考:https://www.jianshu.com/p/0759610fbcdd

  • 4.1 项目修改成war后启动结果


    spring boot项目集成thrift事件交互_第1张图片
    thriftwar.jpg

    从日志中并未发现之前日志中输出的thrift的端口,同时可以打开客户端访问。无法获取到期望的信息。故将项目转成 war后无法启动thrift服务

  • 4.2 解决方案
    以上造成的原因是:jar启动时会新启动一个线程开启thrift的服务,但是war包反正tomcat中不会做这一步操作,需要我们手动完成。
    • 4.2.1 创建thrift监听器
package cn.bintools.daios.example.thrift.listener;

import cn.bintools.daios.example.thrift.server.ThriftServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
 * thrift服务启动监听器
 *
 * @author yunzhe
 * @version 1.0.0 2019-06-20-下午4:36
 */
@Slf4j
public class ThriftServerStartListener implements ServletContextListener {
    private static ThriftServer thriftServer;
    @Override
    public void contextInitialized(ServletContextEvent event) {
        try {
            ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
            thriftServer = context.getBean(ThriftServer.class);
            thriftServer.start();
        }catch (Exception e){
            log.error("开始thrift异常");
            e.printStackTrace();
        }
    }
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}
  • 4.2.2 通过config注册监听器
package cn.bintools.daios.example.thrift.config;

import cn.bintools.daios.example.thrift.listener.ThriftServerStartListener;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * config 注册Thrift监听器
 *
 * @author yunzhe
 * @version 1.0.0 2019-07-02-下午8:11
 */
@Configuration
public class ThrfitConfig {

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    public ServletListenerRegistrationBean listenerRegist() {
        ServletListenerRegistrationBean srb = new ServletListenerRegistrationBean();
        srb.setListener(new ThriftServerStartListener());
        return srb;
    }
}
  • 4.2.3 修改thrift服务开启方法
    通过新创建线程的方式处理,原因:thrift服务启动会一直监听相应的端口,如果不使用新线程监听则导致整个系统无法往下执行。可能项目都无法启动
  public void start(){
        new Thread(){
            @Override
            public void run(){
                TProcessor processor = new HelloService.Processor(new HelloServiceImpl());
                init();
                try{
                    TServerSocket serverSocket = new TServerSocket(port);
                    TThreadPoolServer.Args args = new TThreadPoolServer.Args(serverSocket);
                    args.protocolFactory(protocolFactory);
                    args.processor(processor);
                    args.transportFactory(transportFactory);
                    TServer server = new TThreadPoolServer(args);
                    log.info("thrift server start success, port={}",port);
                    server.serve();
                }catch (TTransportException e){
                    log.error("thrift server start fail",e);
                }
            }
        }.start();
    }
  • 4.2.4 修改启动类
    由于thrift的线程通过监听器进行启动,故需要将启动类还原成默认的生成的类。
package cn.bintools.daios.example.thrift;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
    public static void main(String[] args) { 
        SpringApplication.run(DemoApplication.class, args);
    }
}

通过以上修改,thrift服务将进行正常启动,正常监听相应的端口。具体结果信息:

thriftwarResult.jpg

码云地址 : https://gitee.com/huangjian163/springbootwar_thrift.git

五、总结

通过以上处理,我们可以将thrift集成到spring boot的jar/war项目并可以进行相应的监听。以上的事例都是客户端请求,服务端返回具体的值,如何在监听到thrift操作时进行业务处理呢?请查看下一篇文章--->地址:https://www.jianshu.com/p/44a373192912

你可能感兴趣的:(spring boot项目集成thrift事件交互)