-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathStartGatewayServer.java
127 lines (113 loc) · 5.89 KB
/
StartGatewayServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package io.reactivex.lab.gateway;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.reactivex.lab.gateway.routes.RouteForDeviceHome;
import io.reactivex.lab.gateway.routes.mock.TestRouteBasic;
import io.reactivex.lab.gateway.routes.mock.TestRouteWithHystrix;
import io.reactivex.lab.gateway.routes.mock.TestRouteWithSimpleFaultTolerance;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.pipeline.PipelineConfigurators;
import io.reactivex.netty.protocol.http.server.HttpServerRequest;
import io.reactivex.netty.protocol.http.server.HttpServerResponse;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Subscriber;
import rx.subscriptions.Subscriptions;
import com.netflix.hystrix.HystrixRequestLog;
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsPoller;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
public class StartGatewayServer {
public static void main(String... args) {
// hystrix stream => http://localhost:9999
startHystrixMetricsStream();
System.out.println("Server => Starting at http://localhost:8080/");
System.out.println(" Sample URLs: ");
System.out.println(" - /device/home");
System.out.println(" - /helloworld.js");
System.out.println(" - /hello.js?name=Dave");
System.out.println(" - /async.js");
System.out.println("----------------------------------------------------------------");
// start web services => http://localhost:8080
RxNetty.createHttpServer(8080, (request, response) -> {
System.out.println("Server => Request: " + request.getPath());
return Observable.defer(() -> {
HystrixRequestContext.initializeContext();
try {
return handleRoutes(request, response);
} catch (Throwable e) {
System.err.println("Server => Error [" + request.getPath() + "] => " + e);
response.setStatus(HttpResponseStatus.BAD_REQUEST);
return response.writeStringAndFlush("Error 500: Bad Request\n" + e.getMessage() + "\n");
}
}).onErrorResumeNext(error -> {
System.err.println("Server => Error: " + error.getMessage());
error.printStackTrace();
return writeError(request, response, "Failed: " + error.getMessage());
}).doOnTerminate(() -> {
if (HystrixRequestContext.isCurrentThreadInitialized()) {
System.out.println("Server => Hystrix Log [" + request.getPath() + "] => " + HystrixRequestLog.getCurrentRequest().getExecutedCommandsAsString());
HystrixRequestContext.getContextForCurrentThread().shutdown();
} else {
System.err.println("HystrixRequestContext not initialized for thread: " + Thread.currentThread());
}
});
}).startAndWait();
}
/**
* Hard-coded route handling.
*/
private static Observable<Void> handleRoutes(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) {
if (request.getPath().equals("/device/home")) {
return RouteForDeviceHome.getInstance().handle(request, response);
} else if (request.getPath().equals("/testBasic")) {
return TestRouteBasic.handle(request, response);
} else if (request.getPath().equals("/testWithSimpleFaultTolerance")) {
return TestRouteWithSimpleFaultTolerance.handle(request, response);
} else if (request.getPath().equals("/testWithHystrix")) {
return TestRouteWithHystrix.handle(request, response);
} else {
return writeError(request, response, "Unknown path: " + request.getPath());
}
}
private static void startHystrixMetricsStream() {
RxNetty.createHttpServer(9999, (request, response) -> {
System.out.println("Server => Start Hystrix Stream at http://localhost:9999");
response.getHeaders().add("content-type", "text/event-stream");
return Observable.create((Subscriber<? super Void> s) -> {
s.add(streamPoller.subscribe(json -> {
response.writeStringAndFlush("data: " + json);
}, error -> {
s.onError(error);
}));
s.add(Observable.interval(1000, TimeUnit.MILLISECONDS).flatMap(n -> {
return response.writeStringAndFlush("ping:")
.onErrorReturn(e -> {
System.out.println("Connection closed, unsubscribing from Hystrix Stream");
s.unsubscribe();
return null;
});
}).subscribe());
});
}, PipelineConfigurators.<ByteBuf> serveSseConfigurator()).start();
}
final static Observable<String> streamPoller = Observable.create((Subscriber<? super String> s) -> {
try {
System.out.println("Server => Start Hystrix Metric Poller");
HystrixMetricsPoller poller = new HystrixMetricsPoller(json -> {
s.onNext(json);
}, 1000);
s.add(Subscriptions.create(() -> {
System.out.println("Server => Shutdown Hystrix Stream");
poller.shutdown();
}));
poller.start();
} catch (Exception e) {
s.onError(e);
}
}).publish().refCount();
public static Observable<Void> writeError(HttpServerRequest<?> request, HttpServerResponse<ByteBuf> response, String message) {
System.err.println("Server => Error [" + request.getPath() + "] => " + message);
response.setStatus(HttpResponseStatus.BAD_REQUEST);
return response.writeStringAndFlush("Error 500: " + message);
}
}