Solon v2.7.6

使用 Socket.D

</> markdown
  • 引入依赖包
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>socketd-transport-netty</artifactId>
    <version>${socketd.version}</version>
</dependency>
  • 添加配置器
@Configuration
public class SdConfig {
    @Bean
    public ClientSession clientSession() throws IOException{
        return SocketD.createClient("sd:tcp://127.0.0.1:18602").open();
    }
}
  • 使用 ClientSession
@Controller
public class DemoController {
    @Inject
    ClientSession clientSession;
    
    @Mapping("/hello")
    public Mono<String> mono(String name) throws Exception {
        clientSessionInit();

        return Mono.create(sink -> {
            try {
                Entity entity = new StringEntity("hello")
                        .metaPut("name", name == null ? "noear" : name);

                clientSession.sendAndRequest("hello", entity).thenReply(reply -> {
                    sink.success(reply.dataAsString());
                }).thenError(e -> {
                    sink.error(e);
                });
            } catch (Throwable e) {
                sink.error(e);
            }
        });
    }
    
    @Mapping("/hello2")
    public Flux<String> flux(String name) throws Exception {
        clientSessionInit();
        
        return Flux.create(sink->{
            try {
                Entity entity = new StringEntity("hello")
                        .metaPut("name", name == null ? "noear" : name)
                        .range(5, 5);

                clientSession.sendAndSubscribe("hello", entity).thenReply(reply -> {
                    sink.next(reply.dataAsString());
                    
                    if(reply.isEnd()){
                        sink.complete();
                    }
                }).thenError(e -> {
                    sink.error(e);
                });
            } catch (Throwable e) {
                sink.error(e);
            }
        });
    }
}