工作生活

spring boot项目集成thrift事件交互

2019-07-01  本文已影响0人  5eac0cfdd510

一、前言

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

二、项目构建

<dependency>
    <groupId>org.apache.thrift</groupId>
    <artifactId>libthrift</artifactId>
    <version>0.12.0</version>
</dependency>
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.8</version>
   <optional>true</optional>
</dependency>
#由于生成的文件较大,不展示进行简单说明
ConnectionInfo :根据thrift语言自定义的对象
HelloService:此文件为主要文件,包含我们需要实现的接口Iface
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 <a href="jian.huang@bintools.cn">yunzhe</a>
 * @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<HelloRpcController> processor = new HelloService.Processor<HelloRpcController>(new HelloRpcController());
        TProcessor processor = new HelloService.Processor<HelloService.Iface>(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);
        }
    }
}    
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 <a href="jian.huang@bintools.cn">yunzhe</a>
 * @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;
    }
}
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();
        }
    }
}
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 <a href="jian.huang@bintools.cn">yunzhe</a>
 * @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();
        }
    }
}  

三、结果展示

四、jar项目转war项目

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

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 <a href="jian.huang@bintools.cn">yunzhe</a>
 * @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) {
    }
}
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 <a href="jian.huang@bintools.cn">yunzhe</a>
 * @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;
    }
}
  public void start(){
        new Thread(){
            @Override
            public void run(){
                TProcessor processor = new HelloService.Processor<HelloService.Iface>(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();
    }
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

上一篇下一篇

猜你喜欢

热点阅读