Java从零开始手RPC—怎样实现客户端调用服务端?
发布时间:2021-10-19 09:55:20 所属栏目:语言 来源:互联网
导读:写完了客户端和服务端,那么如何实现客户端和服务端的调用呢? 下面就让我们一起来看一下。 接口定义 计算方法 package com.github.houbb.rpc.common.service; import com.github.houbb.rpc.common.model.CalculateRequest; import com.github.houbb.rpc.comm
写完了客户端和服务端,那么如何实现客户端和服务端的调用呢?
下面就让我们一起来看一下。
接口定义
计算方法
package com.github.houbb.rpc.common.service;
import com.github.houbb.rpc.common.model.CalculateRequest;
import com.github.houbb.rpc.common.model.CalculateResponse;
/**
* <p> 计算服务接口 </p>
*
* <pre> Created: 2018/8/24 下午4:47 </pre>
* <pre> Project: fake </pre>
*
* @author houbinbin
* @since 0.0.1
*/
public interface Calculator {
/**
* 计算加法
* @param request 请求入参
* @return 返回结果
*/
CalculateResponse sum(final CalculateRequest request);
}
pojo
对应的参数对象:
CalculateRequest
package com.github.houbb.rpc.common.model;
import java.io.Serializable;
/**
* <p> 请求入参 </p>
*
* <pre> Created: 2018/8/24 下午5:05 </pre>
* <pre> Project: fake </pre>
*
* @author houbinbin
* @since 0.0.3
*/
public class CalculateRequest implements Serializable {
private static final long serialVersionUID = 6420751004355300996L;
/**
* 参数一
*/
private int one;
/**
* 参数二
*/
private int two;
public CalculateRequest() {
}
public CalculateRequest(int one, int two) {
this.one = one;
this.two = two;
}
//getter setter toString
}
CalculateResponse
package com.github.houbb.rpc.common.model;
import java.io.Serializable;
/**
* <p> 请求入参 </p>
*
* <pre> Created: 2018/8/24 下午5:05 </pre>
* <pre> Project: fake </pre>
*
* @author houbinbin
* @since 0.0.3
*/
public class CalculateResponse implements Serializable {
private static final long serialVersionUID = -1972014736222511341L;
/**
* 是否成功
*/
private boolean success;
/**
* 二者的和
*/
private int sum;
public CalculateResponse() {
}
public CalculateResponse(boolean success, int sum) {
this.success = success;
this.sum = sum;
}
//getter setter toString
}
客户端
核心部分
RpcClient 需要添加对应的 Handler,调整如下:
Bootstrap bootstrap = new Bootstrap();
ChannelFuture channelFuture = bootstrap.group(workerGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<Channel>(){
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline()
.addLast(new LoggingHandler(LogLevel.INFO))
.addLast(new CalculateRequestEncoder())
.addLast(new CalculateResponseDecoder())
.addLast(new RpcClientHandler());
}
})
.connect(RpcConstant.ADDRESS, port)
.syncUninterruptibly();
netty 中的 handler 泳道设计的非常优雅,让我们的代码可以非常灵活地进行拓展。
(编辑:湘西站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |