Skip to content

RPC调用

Xiao Yu edited this page Jun 2, 2019 · 1 revision

服务提供者代码:

public class RpcServerTest {
    public static void main(String[] args) {
        
        //配置RPC服务提供者
        ServerConfig config = new ServerConfig();
        config.addService(HelloService.class.getName(), new HelloServiceImpl());
        config.addService(GreetingService.class.getName(), new GreetingServiceImpl());

        //按需配置安全证书
        SSLContext ssl = SSLUtils.createSSLContext(ClassLoader.getSystemResourceAsStream("test.pfx"), null, "7hukgn0h");

        YrpcServer yrpcServer;
        if (null == ssl) {
            yrpcServer = new YrpcServer(1111, config);
        } else {
            yrpcServer = new YrpcServer(1111, ssl, config);
        }
        System.out.println("启动结果:" + yrpcServer.isOpen());

    }
}

服务消费者代码:

public class RpcClientTest {
    public static void main(String[] args) throws Exception {

        //定义客户端
        YrpcClient yrpcClient = new YrpcClient("127.0.0.1", 1111, SSLUtils.createSSLContext());

        //定义服务代理工厂,用于生成RPC服务消费者
        ServiceProxyFactory serviceProxyFactory = new ServiceProxyFactory(yrpcClient);
        //生成RPC服务消费者
        HelloService helloService = serviceProxyFactory.newServiceProxy(HelloService.class);
        GreetingService greetingService = serviceProxyFactory.newServiceProxy(GreetingService.class);

        IntStream.range(0, 100).parallel().forEach(value -> {
            String rs = helloService.sayHi("张三", 123);
            greetingService.a("a李四");
            String b = greetingService.b("b王五");
            String c = greetingService.c();
            greetingService.d();
            System.out.println(rs + "," + b + "," + c);
        });
    }
}
Clone this wiki locally