我有一个项目,该过程将http请求发送到必须处理长http请求的Web服务器,但如果其中一个服务器崩溃,我需要重新发送崩溃的Web服务器计算到另一个Web服务器的请求这是有用的。
问题是在我的解决方案中我已经发送了IOException标头。该项目的代码很大,所以我构建了一些流程样本,重定向请求以尝试解决此问题,这里是:
import java.io.IOException;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Principal {
static Request request;
public static void main(String[] args) throws IOException
{
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/f.html", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
System.out.println("Server ready");
}
public static void resend()
{
Thread thread = new MyThread(request.getRequest(), "52.18.4.134");
thread.start();
}
static class MyHandler implements HttpHandler
{
@Override
public void handle(HttpExchange t) throws IOException {
request = new Request("30",t);
//each request received will be treated by a different thread
Thread thread = new MyThread(t, "52.31.116.250");
//Thread thread = new Connection.MyThread(t, "52.50.47.25");
thread.start();
}
}
static class MyThread extends Thread
{
private String numeroFatorizar;
String query;
HttpExchange t;
private String destinationIP; //IP of the instance to send the request
public MyThread(HttpExchange t, String destinationIP)
{
this.destinationIP = destinationIP;
this.t = t;
query = t.getRequestURI().getQuery();
if(query != null)
{
String[] parts = query.split("=");
numeroFatorizar = parts[1];
}
}
@Override
public void run()
{
//redirects to web servers
try {
t.getResponseHeaders().add("Location", "http://"+destinationIP+":8000/f.html/numeroFatorizar?="+numeroFatorizar);
t.sendResponseHeaders(301,0);
t.getResponseBody().close();
resend();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
当调用resend()尝试发送到不同的IP时,我会收到“已发送的标题”。我需要向第二个IP发送相同的http请求,因为它包含响应对象。
我在开头就有的请求代码就是这样:
public class Request {
//classe que carateriza um pedido
private String parameter; //parameter to be factorized
private HttpExchange request; //contains client request
public Request(String parameter, HttpExchange request)
{
this.parameter = parameter;
this.request = request;
}
public HttpExchange getRequest() {
return request;
}
}