Solon

SocketD 单链接双向RPC模式

本案以单链接双向RPC模式为例演示:(在RPC调用模式基础上,增加服务端反向接口调用)

1、接口定义

Rpc 模式借用了 Nami 做客户端定义(Nami 是 Solon 伴生框架,定位为 Rpc 通用客户端)

@NamiClient("demo:/demoe/rpc")
public interface HelloService {
    String hello(String name);
}

@NamiClient("demo:/demoe/rpc/name")
public interface NameService {
    String name(String name);
}

2、服务端

//启动服务端
public class ServerApp {
    public static void main(String[] args) {
        //启动Solon容器(SocketD bean&plugin 由solon容器管理)
        Solon.start(ServerApp.class, args, app -> app.enableSocketD(true));
    }
}

//定义远程服务组件(供客户端调用)
@Mapping(value = "/demoe/rpc", method = MethodType.SOCKET)
@Component(remoting = true)
public class HelloServiceImpl implements HelloService {
    public String hello(String name) {
        //[服务端] 反向调用 [客户端] 的远程服务组件***
        NameService rpc = SocketD.create(Context.current(), NameService.class);
        name = rpc.name(name);
    
        return "name=" + name;
    }
}

3、客户端

//启动客户端
public class ClientApp {
    public static void main(String[] args) throws Throwable {
        //启动Solon容器(SocketD bean&plugin 由solon容器管理)
        Solon.start(ClientApp.class, args);
        
        //[客户端] 调用 [服务端] 的 rpc
        //
        HelloService rpc = SocketD.create("tcp://localhost:28080", HelloService.class);

        System.out.println("RPC result: " + rpc.hello("noear"));
    }
}

//定义远程服务组件(供服务端调用)
@Mapping(value = "/demoe/rpc/name", method = MethodType.SOCKET)
@Component(remoting = true)
public class NameServiceImpl implements NameService {
    @Override
    public String name(String name) {
        return name + "2";
    }
}