java服务端
package com.xx.thrift;
import org.apache.thrift.TMultiplexedProcessor;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.ServerSocket;
@Configuration
public class Server {
@Value("${thrift.port}")
private int servicePort;
@Autowired
private PdfSignService.Iface pdfService;
@Autowired
private HkVideoService.Iface videoService;
@PostConstruct
public void startServer() {
try {
System.out.println(servicePort);
ServerSocket socket = null;
try {
socket = new ServerSocket(servicePort);
} catch (IOException e) {
e.printStackTrace();
}
TServerSocket serverTransport = new TServerSocket(socket);
// thrift多服务
TMultiplexedProcessor multiplexedProcessor = new TMultiplexedProcessor();
// 服务1
multiplexedProcessor.registerProcessor("PdfService", new PdfSignService.Processor<>(pdfService));
// 服务2
multiplexedProcessor.registerProcessor("HkVideoService", new HkVideoService.Processor<>(videoService));
TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport);
TBinaryProtocol.Factory proFactory = new TBinaryProtocol.Factory();
serverArgs.processor(multiplexedProcessor);
serverArgs.protocolFactory(proFactory);
TServer server = new TThreadPoolServer(serverArgs);
System.out.println("Start server on port : " + servicePort);
server.serve();
} catch (TTransportException e) {
e.printStackTrace();
}
}
}
python客户端
@contextmanager
def get_pdf_client():
transport = None
try:
transport = TSocket.TSocket(THRIFT_HOST, THRIFT_PORT)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
transport.open()
pdf_protocol = TMultiplexedProtocol.TMultiplexedProtocol(protocol, "PdfService")
pdf_client = PdfClient(pdf_protocol)
yield pdf_client
finally:
if transport is not None:
transport.close()