starlight icon indicating copy to clipboard operation
starlight copied to clipboard

启动多个server,最后一个会覆盖之前所有

Open Delostik opened this issue 5 years ago • 2 comments

简化场景:某服务提供一个ping接口,在response的data字段中返回自己的名字。

EchoService.java

package com.test;

import com.baidu.brpc.protocol.BrpcMeta;
import com.test.proto.PingRequest;
import com.test.proto.PingResponse;

public interface EchoService {
    @BrpcMeta(serviceName = "testproto.EchoService", methodName = "Ping")
    PingResponse ping(PingRequest request);
}

EchoServiceImpl.java

package com.test;

import com.google.protobuf.ByteString;
import com.test.proto.PingRequest;
import com.test.proto.PingResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EchoServiceImpl implements EchoService {
    private static final Logger LOG = LoggerFactory.getLogger(EchoServiceImpl.class);
    private final String message;

    public EchoServiceImpl(String s) {
        this.message = s;
    }

    @Override
    public PingResponse ping(PingRequest request) {
        PingResponse response = PingResponse.newBuilder().setData(ByteString.copyFromUtf8(message)).build();
        LOG.info(" response data={}", message);
        return response;
    }
}

Demo.java

package com.test;

import com.baidu.brpc.client.BrpcProxy;
import com.baidu.brpc.client.RpcClient;
import com.baidu.brpc.client.RpcClientOptions;
import com.baidu.brpc.protocol.Options;
import com.baidu.brpc.server.RpcServer;
import com.test.proto.PingRequest;
import com.test.proto.PingResponse;

public class MultiServer {
    public static void main(String[] args) throws InterruptedException {
        final RpcServer rpcServer = new RpcServer(8092);
        rpcServer.registerService(new EchoServiceImpl("serverA"));
        rpcServer.start();

        final RpcServer rpcServer2 = new RpcServer(8093);
        rpcServer2.registerService(new EchoServiceImpl("serverB"));
        rpcServer2.start();

        RpcClientOptions clientOption = new RpcClientOptions();
        clientOption.setProtocolType(Options.ProtocolType.PROTOCOL_BAIDU_STD_VALUE);

        ClientPingRequest request = ClientPingRequest.newBuilder().build();
        RpcClient rpcClient = new RpcClient("list://127.0.0.1:8092", clientOption);
        EchoService echoService = BrpcProxy.getProxy(rpcClient, EchoService.class);
        ClientPingResponse response = echoService.ping(request);
        System.out.println(response.getData().toStringUtf8());
    }
}

不管请求发给哪个端口,返回都是serverB。如果注册更多server,永远返回的是最后注册的那个。

Delostik avatar Oct 29 '20 06:10 Delostik

看起来好像是因为serviceManager是单例,serviceMap只用了method name和service name做key……感觉这个是不是不太友好。。grpc并不是这样的……

Delostik avatar Oct 29 '20 06:10 Delostik

+1 这个不太友好

psylambda avatar Jul 08 '21 12:07 psylambda