简体   繁体   English

Netty的异步应用程序设计

[英]Asynchronous Application Design With Netty

I have a server Foo, that I connect to via a simple socket. 我有一个服务器Foo,可以通过一个简单的套接字连接到它。 I write text into the socket to send it messages and it replies with a response to my query once it's processed it, however it makes no guarantee of the order of responses. 我在套接字中写入文本以发送消息,处理完后它会回复我的查询,但是不能保证响应的顺序。 I can link up requests and responses with IDs. 我可以用ID链接请求和响应。

Ex : 例如:

Send "1:request" to Foo
Foo Returns "1:response"

Send "1:request" & "2:request" to Foo
Foo Returns "2:response"
10 seconds later
Foo Returns "1:response"

Question: 题:

What's the best way to handle this situation with Netty, how can I provide an interface that allows me to submit a message to the Foo service and give me a Promise or a Future that allows me to return without blocking waiting for the response to my message (but knowing i have an object that I can block on later) 使用Netty处理这种情况的最佳方法是什么,如何提供允许我向Foo服务提交消息的界面,并给我一个Promise或Future来允许我返回而不会阻塞等待对消息的响应(但知道我有一个以后可以阻止的对象)

One way to do that is by sharing a data-structure between your response handler (ie the last handler in the pipeline of your client) and the client that shoots the requests. 一种实现方法是在响应处理程序(即客户端管道中的最后一个处理程序)与发出请求的客户端之间共享数据结构。 For example, it can be a map with your ID and a blocking queue where the response will be put by the handler. 例如,它可以是具有您的ID和阻止队列的映射,处理程序将在其中放置响应。

The send message in your client would be something like: 您的客户端中的发送消息类似于:

public Future send(String id, String msg) {
  BlockingQueue queue = new ArrayBlockingQueue(1);
  handler.responses().put(id, queue);
  channel.writeAndFlush(id + ":" + msg);
  return new MyFuture(queue);
}

Then, the thread that called send() can wait for the response with myFuture.get() , which will have an implementation that blocks on the queue you passed in the constructor, eg: 然后,调用send()的线程可以等待myFuture.get()的响应,该线程的实现会阻塞在构造函数中传递的队列,例如:

@Override
public String get() throws InterruptedException, ExecutionException {
  return queue.take();
}

Checkout the HTTP/2 example for another approach (still quite similar): https://github.com/netty/netty/blob/4.1/example/src/main/java/io/netty/example/http2/client/HttpResponseHandler.java 签出HTTP / 2示例以获取另一种方法(仍然非常相似): https : //github.com/netty/netty/blob/4.1/example/src/main/java/io/netty/example/http2/client/HttpResponseHandler的.java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM