手写RPC---⑨实现client模块(上)

终于来到了最后一章:client模块
在client包下新建一个server选择的路由接口:

接口

//server选择的路由:表示选择哪个server去连接
public interface TransportSelector {
    //初始化 参数1:server的全部网络端点(信息) 参数2:client和server建立多少个连接
    //参数3:TransportClient接口 -> client实现类的信息
    void init(List<Peer> peers,int count,
            Class<? extends  TransportClient>  clazz );
            
    //方法1:选择一个Transport去和server做交互   返回网络client
    TransportClient select();
    
    //方法2:释放client
    void release(TransportClient client);
    
    //关闭
    void close();
}

实现类

@Slf4j
public class RandomTransportSelector implements TransportSelector {
    //已经连接好的client
    private List<TransportClient> clients;

    public RandomTransportSelector() {
        this.clients = new ArrayList<>();
    }

    @Override
    public synchronized void init(List<Peer> peers, int count, Class<? extends TransportClient> clazz) {
            //count 必须是大于等于1的
            count = Math.max(count,1);
            //遍历端点
        for (Peer peer : peers) {
            //拿到要连接的客户端对象
            TransportClient client = ReflectionsUtils.newInstance(clazz);
            //连接
            client.connect(peer);
            clients.add(client);
            log.info("connect server: {}",peer);
        }
    }

    @Override
    public synchronized TransportClient select() {
        //采用随机的方式
        //随机从clients池中 返回一个client(client网络)
        int i = new Random().nextInt(clients.size()) ;
        return clients.remove(i);

    }

    @Override
    public synchronized void release(TransportClient client) {
            clients.add(client);//加入池里面 下次用
    }

    @Override
    public synchronized void close() {
        for (TransportClient client : clients) {
            client.close();
        }
        clients.clear();
    }
}

配置类

@Data
//配置类
public class RpcClientConfig {
    //哪一个网络模块的实现 (client类的实现类型)
    private  Class<? extends TransportClient> transportClass =
            HTTPTransportClient.class;
    //序列化类型
    private  Class<? extends Encoder> encoderClass = JSONEncoder.class;
    private  Class<? extends Decoder> decoderClass = JSONDecoder.class;
    //路由选择
    private  Class<? extends TransportSelector> selectorClass = RandomTransportSelector.class;
    //每一个server的peer需要建立多少个连接 默认1
    private  int connectCount = 1;
    //可以连哪些网络端点                                      默认值本地IP 端口3000
    private List<Peer> servers = Arrays.asList(new Peer("127.0.0.1",3000));



}

你可能感兴趣的:(手写一个简单的PRC,rpc,java,网络,网络协议)