java实现Thrift服务端和客户端

本文将详细介绍如何使用Java实现Thrift服务端和客户端。通过创建`DemoService.java`接口定义服务,然后在`MyServer.java`中实现服务端逻辑,最后构建客户端调用这些服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

namespace java service.test

service Demo {
    string sayWord(1:string word)
}

DemoService.java

package service.test;

import org.apache.thrift.TException;
import service.test.Demo.Iface;

public class DemoService implements Iface {

	@Override
	public String sayWord(String word) throws TException {
		System.out.println("receive " + word);
		return "hello " + word;
	}
}

MyServer.java

package service.test;

import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TBinaryProtocol.Factory;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.server.TThreadPoolServer.Args;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;

public class MyServer {
	
	public void startServer() {
		try {
			TServerSocket serverTransport = new TServerSocket(8989);
			Demo.Processor process = new Demo.Processor(new DemoService());
			Factory portFactory = new TBinaryProtocol.Factory(true, true);
			Args args = new Args(serverTransport);
			args.processor(process);
			args.protocolFactory(portFactory);
			TServer server = new TThreadPoolServer(args);
			server.serve();
		} catch (TTransportException e) {
			e.printStackTrace();
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyServer server = new MyServer();
		server.startServer();
	}

}
Client.java

package service.test;

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;

public class Client {

	public void startClient() {
		TTransport transport;
		try {
			transport = new TSocket("localhost", 8989);
			TProtocol protocol = new TBinaryProtocol(transport);
			Demo.Client client = new Demo.Client(protocol);
			transport.open();
			System.out.println(client.sayWord("welcome to use thrift..."));
			transport.close();
		} catch (TTransportException e) {
			e.printStackTrace();
		} catch (TException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Client client = new Client();
		client.startClient();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值