RPC框架技术选型与架构设计
RPC,全称为 Remote Procedure Call(远程过程调用),其核心概念在于让开发者能够像调用本地方法一样,去执行部署在远程计算机上的服务逻辑。
RPC 的实现通常依赖于 HTTP 或 TCP 协议。Web Service 是基于 HTTP 协议的 RPC 典型代表,虽然具备良好的跨平台兼容性,但性能表现不及基于 TCP 协议的 RPC。影响 RPC 性能的关键因素主要包括数据传输方式以及数据序列化机制两个方面。
从网络分层来看,TCP 属于传输层协议,而 HTTP 属于应用层协议。由于传输层比应用层更底层,在数据传输效率上,底层协议通常更快,因此一般情况下 TCP 的传输速度优于 HTTP。在序列化方面,尽管 Java 提供了默认的序列化机制,但在高并发场景下容易成为性能瓶颈。为此,市场上涌现出 Protobuf、Kryo、Hessian、Jackson 等优秀的序列化框架,它们能替代 Java 默认方案,提供更高效的性能表现。
为了应对高并发需求,传统的阻塞式 IO 已不再适用,必须引入异步 IO,即 NIO。Java 原生提供了 NIO 解决方案,且 Java 7 引入了更完善的 NIO.2 支持。虽然实现 NIO 需要掌握一定的技术细节,但这并非遥不可及的目标。
在分布式环境中,服务需部署于不同节点,并通过服务注册机制让客户端自动发现并调用可用服务。这需要引入服务注册表(Service Registry)组件,用于集中管理分布式环境下所有服务的地址信息,包括主机名与端口号。
应用、服务与服务注册表之间的交互关系如图所示:

每台 Server 可发布多个 Service,这些 Service 共享相同的 host 与 port。在分布式架构中,多台 Server 共同对外提供服务。此外,为避免 Service Registry 出现单点故障,应将其搭建为集群环境。
本文将详细阐述开发轻量级分布式 RPC 框架的具体步骤。该框架基于 TCP 协议,集成 NIO 特性,采用高效序列化方式,并具备服务注册与发现能力。
根据上述技术需求,推荐的技术选型如下:
- Spring:作为业界权威的依赖注入框架,功能强大且标准统一。
- Netty:简化 NIO 编程,屏蔽 Java 底层 NIO 的复杂细节。
- Protostuff:基于 Protobuf 的序列化框架,面向 POJO,无需编写 .proto 文件。
- ZooKeeper:提供可靠的服务注册与发现功能,是开发分布式系统的首选,且天然支持集群部署。
相关的 Maven 依赖配置详见文末附录。
RPC框架开发与实现步骤
第一步:定义服务接口
public interface HelloService {
String hello(String name);
}
将该接口打包至独立的客户端 jar 包中,供应用端引用使用。
第二步:编写服务接口的实现类
@RpcService(HelloService.class) // 指定远程接口
public class HelloServiceImpl implements HelloService {
@Override
public String hello(String name) {
return "Hello! " + name;
}
}
在服务接口的实现类上使用 @RpcService 注解,并指定远程接口。因为一个实现类可能实现多个接口,必须明确告知框架哪个才是需要暴露的远程接口。
@RpcService 注解的代码实现如下:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Component // 表明可被 Spring 扫描
public @interface RpcService {
Class<?> value();
}
该注解具备 Spring 的 @Component 特性,能够被 Spring 容器扫描并注册。
该实现类应放置在服务端 jar 包中,该 jar 包还包含服务端配置文件及启动服务的引导程序。
第三步:配置服务端参数
服务端的 Spring 配置文件命名为 spring.xml,具体内容如下:
具体的配置参数存储在 config.properties 文件中,内容如下:
# ZooKeeper 服务器
registry.address=127.0.0.1:2181
# RPC 服务器
server.address=127.0.0.1:8000
上述配置表明:连接本地的 ZooKeeper 服务器,并在 8000 端口上发布 RPC 服务。
第四步:启动服务器并发布服务
为了加载 Spring 配置文件以发布服务,只需编写一个简单的引导程序即可:
public class RpcBootstrap {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("spring.xml");
}
}
运行 RpcBootstrap 类的 main 方法即可启动服务端。此时还有两个关键组件尚未实现,分别是 ServiceRegistry 与 RpcServer,下文将给出具体实现细节。
第五步:实现服务注册逻辑
利用 ZooKeeper 客户端可以方便地实现服务注册功能,ServiceRegistry 的代码如下:
public class ServiceRegistry {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegistry.class);
private CountDownLatch latch = new CountDownLatch(1);
private String registryAddress;
public ServiceRegistry(String registryAddress) {
this.registryAddress = registryAddress;
}
public void register(String data) {
if (data != null) {
ZooKeeper zk = connectServer();
if (zk != null) {
createNode(zk, data);
}
}
}
private ZooKeeper connectServer() {
ZooKeeper zk = null;
try {
zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
latch.countDown();
}
}
});
latch.await();
} catch (IOException | InterruptedException e) {
LOGGER.error("", e);
}
return zk;
}
private void createNode(ZooKeeper zk, String data) {
try {
byte[] bytes = data.getBytes();
String path = zk.create(Constant.ZK_DATA_PATH, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
LOGGER.debug("create zookeeper node ({} => {})", path, data);
} catch (KeeperException | InterruptedException e) {
LOGGER.error("", e);
}
}
}
其中,Constant 接口定义了所有使用的常量:
public interface Constant {
int ZK_SESSION_TIMEOUT = 5000;
String ZK_REGISTRY_PATH = "/registry";
String ZK_DATA_PATH = ZK_REGISTRY_PATH + "/data";
}
注意:首先需要使用 ZooKeeper 客户端命令行创建 /registry 永久节点,用于存放所有的服务临时节点。
第六步:实现 RPC 服务器核心逻辑
使用 Netty 可实现一个支持 NIO 的 RPC 服务器,需通过 ServiceRegistry 注册服务地址,RpcServer 代码如下:
public class RpcServer implements ApplicationContextAware, InitializingBean {
private static final Logger LOGGER = LoggerFactory.getLogger(RpcServer.class);
private String serverAddress;
private ServiceRegistry serviceRegistry;
private Map handlerMap = new HashMap<>(); // 存放接口名与服务对象之间的映射关系
public RpcServer(String serverAddress) {
this.serverAddress = serverAddress;
}
public RpcServer(String serverAddress, ServiceRegistry serviceRegistry) {
this.serverAddress = serverAddress;
this.serviceRegistry = serviceRegistry;
}
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
Map serviceBeanMap = ctx.getBeansWithAnnotation(RpcService.class); // 获取所有带有 RpcService 注解的 Spring Bean
if (MapUtils.isNotEmpty(serviceBeanMap)) {
for (Object serviceBean : serviceBeanMap.values()) {
String interfaceName = serviceBean.getClass().getAnnotation(RpcService.class).value().getName();
handlerMap.put(interfaceName, serviceBean);
}
}
}
@Override
public void afterPropertiesSet() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
channel.pipeline()
.addLast(new RpcDecoder(RpcRequest.class)) // 将 RPC 请求进行解码(为了处理请求)
.addLast(new RpcEncoder(RpcResponse.class)) // 将 RPC 响应进行编码(为了返回响应)
.addLast(new RpcHandler(handlerMap)); // 处理 RPC 请求
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true);
String[] array = serverAddress.split(":");
String host = array[0];
int port = Integer.parseInt(array[1]);
ChannelFuture future = bootstrap.bind(host, port).sync();
LOGGER.debug("server started on port {}", port);
if (serviceRegistry != null) {
serviceRegistry.register(serverAddress); // 注册服务地址
}
future.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
以上代码中涉及两个重要的 POJO,分别是 RpcRequest 与 RpcResponse。
RpcRequest 用于封装 RPC 请求,代码如下:
public class RpcRequest {
private String requestId;
private String className;
private String methodName;
private Class<?>[] parameterTypes;
private Object[] parameters;
// getter/setter...
}
RpcResponse 用于封装 RPC 响应,代码如下:
public class RpcResponse {
private String requestId;
private Throwable error;
private Object result;
// getter/setter...
}
RpcDecoder 负责提供 RPC 解码功能,只需扩展 Netty 的 ByteToMessageDecoder 抽象类的 decode 方法即可,代码如下:
public class RpcDecoder extends ByteToMessageDecoder {
private Class<?> genericClass;
public RpcDecoder(Class<?> genericClass) {
this.genericClass = genericClass;
}
@Override
public void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception {
if (in.readableBytes() < 4) {
return;
}
in.markReaderIndex();
int dataLength = in.readInt();
if (dataLength < 0) {
ctx.close();
}
if (in.readableBytes() < dataLength) {
in.resetReaderIndex();
return;
}
byte[] data = new byte[dataLength];
in.readBytes(data);
Object obj = SerializationUtil.deserialize(data, genericClass);
out.add(obj);
}
}
RpcEncoder 负责提供 RPC 编码功能,只需扩展 Netty 的 MessageToByteEncoder 抽象类的 encode 方法即可,代码如下:
public class RpcEncoder extends MessageToByteEncoder {
private Class<?> genericClass;
public RpcEncoder(Class<?> genericClass) {
this.genericClass = genericClass;
}
@Override
public void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception {
if (genericClass.isInstance(in)) {
byte[] data = SerializationUtil.serialize(in);
out.writeInt(data.length);
out.writeBytes(data);
}
}
}
编写 SerializationUtil 工具类,使用 Protostuff 实现序列化操作:
public class SerializationUtil {
private static Map, Schema<?>> cachedSchema = new ConcurrentHashMap<>();
private static Objenesis objenesis = new ObjenesisStd(true);
private SerializationUtil() {
}
@SuppressWarnings("unchecked")
private static Schema getSchema(Class cls) {
Schema schema = (Schema) cachedSchema.get(cls);
if (schema == null) {
schema = RuntimeSchema.createFrom(cls);
if (schema != null) {
cachedSchema.put(cls, schema);
}
}
return schema;
}
@SuppressWarnings("unchecked")
public static byte[] serialize(T obj) {
Class cls = (Class) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema schema = getSchema(cls);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
public static T deserialize(byte[] data, Class cls) {
try {
T message = (T) objenesis.newInstance(cls);
Schema schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(data, message, schema);
return message;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
上述代码使用了 Objenesis 来实例化对象,其功能比 Java 反射更为强大。
注意:如需替换其他序列化框架,只需修改 SerializationUtil 类即可。当然,更优的实现方式是提供配置项来决定使用哪种序列化方式。
RpcHandler 用于处理 RPC 请求,只需扩展 Netty 的 SimpleChannelInboundHandler 抽象类即可,代码如下:
public class RpcHandler extends SimpleChannelInboundHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RpcHandler.class);
private final Map handlerMap;
public RpcHandler(Map handlerMap) {
this.handlerMap = handlerMap;
}
@Override
public void channelRead0(final ChannelHandlerContext ctx, RpcRequest request) throws Exception {
RpcResponse response = new RpcResponse();
response.setRequestId(request.getRequestId());
try {
Object result = handle(request);
response.setResult(result);
} catch (Throwable t) {
response.setError(t);
}
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
}
private Object handle(RpcRequest request) throws Throwable {
String className = request.getClassName();
Object serviceBean = handlerMap.get(className);
Class<?> serviceClass = serviceBean.getClass();
String methodName = request.getMethodName();
Class<?>[] parameterTypes = request.getParameterTypes();
Object[] parameters = request.getParameters();
/*Method method = serviceClass.getMethod(methodName, parameterTypes);
method.setAccessible(true);
return method.invoke(serviceBean, parameters);*/
FastClass serviceFastClass = FastClass.create(serviceClass);
FastMethod serviceFastMethod = serviceFastClass.getMethod(methodName, parameterTypes);
return serviceFastMethod.invoke(serviceBean, parameters);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
LOGGER.error("server caught exception", cause);
ctx.close();
}
}
为了避免使用 Java 反射带来的性能损耗,可以使用 CGLib 提供的反射 API,如代码中用到的 FastClass 与 FastMethod。
第七步:配置客户端环境
同样使用 Spring 配置文件来配置 RPC 客户端,spring.xml 代码如下:
其中 config.properties 提供了具体的配置信息:
# ZooKeeper 服务器
registry.address=127.0.0.1:2181
第八步:实现服务发现机制
同样使用 ZooKeeper 来实现服务发现功能,相关代码如下:
public class ServiceDiscovery {
private static final Logger LOGGER = LoggerFactory.getLogger(ServiceDiscovery.class);
private CountDownLatch latch = new CountDownLatch(1);
private volatile List dataList = new ArrayList<>();
private String registryAddress;
public ServiceDiscovery(String registryAddress) {
this.registryAddress = registryAddress;
ZooKeeper zk = connectServer();
if (zk != null) {
watchNode(zk);
}
}
public String discover() {
String data = null;
int size = dataList.size();
if (size > 0) {
if (size == 1) {
data = dataList.get(0);
LOGGER.debug("using only data: {}", data);
} else {
data = dataList.get(ThreadLocalRandom.current().nextInt(size));
LOGGER.debug("using random data: {}", data);
}
}
return data;
}
private ZooKeeper connectServer() {
ZooKeeper zk = null;
try {
zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getState() == Event.KeeperState.SyncConnected) {
latch.countDown();
}
}
});
latch.await();
} catch (IOException | InterruptedException e) {
LOGGER.error("", e);
}
return zk;
}
private void watchNode(final ZooKeeper zk) {
try {
List nodeList = zk.getChildren(Constant.ZK_REGISTRY_PATH, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeChildrenChanged) {
watchNode(zk);
}
}
});
List dataList = new ArrayList<>();
for (String node : nodeList) {
byte[] bytes = zk.getData(Constant.ZK_REGISTRY_PATH + "/" + node, false, null);
dataList.add(new String(bytes));
}
LOGGER.debug("node data: {}", dataList);
this.dataList = dataList;
} catch (KeeperException | InterruptedException e) {
LOGGER.error("", e);
}
}
}
第九步:实现 RPC 代理逻辑
此处使用 Java 提供的动态代理技术实现 RPC 代理(也可使用 CGLib 实现),具体代码如下:
public class RpcProxy {
private String serverAddress;
private ServiceDiscovery serviceDiscovery;
public RpcProxy(String serverAddress) {
this.serverAddress = serverAddress;
}
public RpcProxy(ServiceDiscovery serviceDiscovery) {
this.serviceDiscovery = serviceDiscovery;
}
@SuppressWarnings("unchecked")
public T create(Class<?> interfaceClass) {
return (T) Proxy.newProxyInstance(
interfaceClass.getClassLoader(),
new Class<?>[]{interfaceClass},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
RpcRequest request = new RpcRequest(); // 创建并初始化 RPC 请求
request.setRequestId(UUID.randomUUID().toString());
request.setClassName(method.getDeclaringClass().getName());
request.setMethodName(method.getName());
request.setParameterTypes(method.getParameterTypes());
request.setParameters(args);
if (serviceDiscovery != null) {
serverAddress = serviceDiscovery.discover(); // 发现服务
}
String[] array = serverAddress.split(":");
String host = array[0];
int port = Integer.parseInt(array[1]);
RpcClient client = new RpcClient(host, port); // 初始化 RPC 客户端
RpcResponse response = client.send(request); // 通过 RPC 客户端发送 RPC 请求并获取 RPC 响应
if (response.isError()) {
throw response.getError();
} else {
return response.getResult();
}
}
}
);
}
}
RpcClient 类用于实现 RPC 客户端,只需扩展 Netty 提供的 SimpleChannelInboundHandler 抽象类即可,代码如下:
public class RpcClient extends SimpleChannelInboundHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RpcClient.class);
private String host;
private int port;
private RpcResponse response;
private final Object obj = new Object();
public RpcClient(String host, int port) {
this.host = host;
this.port = port;
}
@Override
public void channelRead0(ChannelHandlerContext ctx, RpcResponse response) throws Exception {
this.response = response;
synchronized (obj) {
obj.notifyAll(); // 收到响应,唤醒线程
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOGGER.error("client caught exception", cause);
ctx.close();
}
public RpcResponse send(RpcRequest request) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class)
.handler(new ChannelInitializer() {
@Override
public void initChannel(SocketChannel channel) throws Exception {
channel.pipeline()
.addLast(new RpcEncoder(RpcRequest.class)) // 将 RPC 请求进行编码(为了发送请求)
.addLast(new RpcDecoder(RpcResponse.class)) // 将 RPC 响应进行解码(为了处理响应)
.addLast(RpcClient.this); // 使用 RpcClient 发送 RPC 请求
}
})
.option(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().writeAndFlush(request).sync();
synchronized (obj) {
obj.wait(); // 未收到响应,使线程等待
}
if (response != null) {
future.channel().closeFuture().sync();
}
return response;
} finally {
group.shutdownGracefully();
}
}
}
第十步:发送 RPC 请求进行测试
使用 JUnit 结合 Spring 编写一个单元测试,代码如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring.xml")
public class HelloServiceTest {
@Autowired
private RpcProxy rpcProxy;
@Test
public void helloTest() {
HelloService helloService = rpcProxy.create(HelloService.class);
String result = helloService.hello("World");
Assert.assertEquals("Hello! World", result);
}
}
运行以上单元测试,如果一切正常,您应该会看到测试通过的绿条。
总结
本文通过整合 Spring、Netty、Protostuff 和 ZooKeeper,实现了一个轻量级 RPC 框架。Spring 负责依赖注入与参数配置,Netty 实现 NIO 方式的数据传输,Protostuff 负责对象序列化,ZooKeeper 则实现服务的注册与发现。使用该框架,可将服务部署到分布式环境中的任意节点上,客户端通过远程接口透明调用服务端的具体实现,实现了服务端与客户端开发的完全分离,为实现大规模分布式应用提供了基础支持。
附录:Maven 依赖
junit
junit
4.11
test
org.slf4j
slf4j-log4j12
1.7.7
org.springframework
spring-context
3.2.12.RELEASE
org.springframework
spring-test
3.2.12.RELEASE
test
io.netty
netty-all
4.0.24.Final
com.dyuproject.protostuff
protostuff-core
1.0.8
com.dyuproject.protostuff
protostuff-runtime
1.0.8
org.apache.zookeeper
zookeeper
3.4.6
org.apache.commons
commons-collections4
4.0
org.objenesis
objenesis
2.1
cglib
cglib
3.1