Add gateway-mvc: Spring Cloud Gateway Server MVC 5.1 on Boot 4.2.0 + virtual threads, retry, Redis rate limiting
Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b3W3uHbHAmM3orhn7b
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
7211b0fb80
commit
32086c1f5b
@@ -0,0 +1,40 @@
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/** java scripts/LoadClient.java <url> <concurrent requests> : fires them all at once and prints a summary. */
|
||||
public class LoadClient {
|
||||
public static void main(String[] args) throws Exception {
|
||||
String url = args[0];
|
||||
int n = Integer.parseInt(args[1]);
|
||||
Map<Integer, AtomicInteger> statuses = new ConcurrentHashMap<>();
|
||||
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();
|
||||
long t0 = System.nanoTime();
|
||||
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
pool.submit(() -> {
|
||||
int code;
|
||||
try {
|
||||
code = client.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(60)).build(),
|
||||
HttpResponse.BodyHandlers.discarding()).statusCode();
|
||||
} catch (Exception e) {
|
||||
code = -1;
|
||||
}
|
||||
statuses.computeIfAbsent(code, k -> new AtomicInteger()).incrementAndGet();
|
||||
});
|
||||
}
|
||||
pool.shutdown();
|
||||
pool.awaitTermination(2, TimeUnit.MINUTES);
|
||||
}
|
||||
long ms = (System.nanoTime() - t0) / 1_000_000;
|
||||
System.out.println("requests=" + n + " statuses=" + new TreeMap<>(statuses) + " elapsed_ms=" + ms);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
/**
|
||||
* A deliberately boring backend for the gateway to proxy to. No Spring, no dependencies:
|
||||
* java scripts/Upstream.java [port]
|
||||
* Endpoints: /hello, /limited, /slow?ms=500, /flaky?failFirst=2, /flaky/reset, /headers
|
||||
*/
|
||||
public class Upstream {
|
||||
|
||||
static final AtomicInteger flakyCalls = new AtomicInteger();
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
int port = args.length > 0 ? Integer.parseInt(args[0]) : 9091;
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
|
||||
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
|
||||
|
||||
server.createContext("/hello", ex ->
|
||||
send(ex, 200, "{\"service\":\"upstream\",\"message\":\"hello from the backend\"}"));
|
||||
|
||||
server.createContext("/limited", ex ->
|
||||
send(ex, 200, "{\"service\":\"upstream\",\"message\":\"you got through the rate limiter\"}"));
|
||||
|
||||
server.createContext("/slow", ex -> {
|
||||
long ms = Long.parseLong(param(ex, "ms", "500"));
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
send(ex, 200, "{\"slept\":" + ms + "}");
|
||||
});
|
||||
|
||||
server.createContext("/flaky/reset", ex -> {
|
||||
flakyCalls.set(0);
|
||||
send(ex, 200, "{\"reset\":true}");
|
||||
});
|
||||
|
||||
server.createContext("/flaky", ex -> {
|
||||
int failFirst = Integer.parseInt(param(ex, "failFirst", "2"));
|
||||
int n = flakyCalls.incrementAndGet();
|
||||
if (n <= failFirst) {
|
||||
send(ex, 503, "{\"call\":" + n + ",\"result\":\"unavailable\"}");
|
||||
} else {
|
||||
send(ex, 200, "{\"call\":" + n + ",\"result\":\"ok\"}");
|
||||
}
|
||||
});
|
||||
|
||||
server.createContext("/headers", ex -> {
|
||||
Map<String, String> sorted = new TreeMap<>();
|
||||
ex.getRequestHeaders().forEach((k, v) -> sorted.put(k.toLowerCase(), String.join(",", v)));
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sorted.forEach((k, v) -> sb.append(k).append(": ").append(v).append('\n'));
|
||||
ex.getResponseHeaders().set("Content-Type", "text/plain");
|
||||
byte[] b = sb.toString().getBytes(StandardCharsets.UTF_8);
|
||||
ex.sendResponseHeaders(200, b.length);
|
||||
ex.getResponseBody().write(b);
|
||||
ex.close();
|
||||
});
|
||||
|
||||
server.start();
|
||||
System.out.println("upstream listening on " + port);
|
||||
}
|
||||
|
||||
static String param(HttpExchange ex, String name, String def) {
|
||||
String q = ex.getRequestURI().getQuery();
|
||||
if (q == null) return def;
|
||||
for (String kv : q.split("&")) {
|
||||
String[] p = kv.split("=", 2);
|
||||
if (p[0].equals(name) && p.length == 2) return p[1];
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
static void send(HttpExchange ex, int status, String body) throws IOException {
|
||||
byte[] b = body.getBytes(StandardCharsets.UTF_8);
|
||||
ex.getResponseHeaders().set("Content-Type", "application/json");
|
||||
ex.sendResponseHeaders(status, b.length);
|
||||
ex.getResponseBody().write(b);
|
||||
ex.close();
|
||||
}
|
||||
}
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
# Source me. Picks JDK 25 if present at /tmp/tools, otherwise whatever java is on PATH.
|
||||
if [ -d /tmp/tools/jdk-25.0.5.1+2 ]; then export JAVA_HOME=/tmp/tools/jdk-25.0.5.1+2; export PATH=$JAVA_HOME/bin:$PATH; fi
|
||||
export JAVA_TOOL_OPTIONS= _JAVA_OPTIONS=
|
||||
Executable
+33
@@ -0,0 +1,33 @@
|
||||
# Shared helpers. Source me from the other scripts.
|
||||
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
. "$HERE/scripts/env.sh"
|
||||
JAR="$HERE/target/gateway-mvc-1.0.0.jar"
|
||||
LOGDIR="${LOGDIR:-/tmp/gwmvc-logs}"; mkdir -p "$LOGDIR"
|
||||
|
||||
# Kill by main-class pattern kept in a variable so this very script's command line never matches it.
|
||||
stop_all() {
|
||||
local pat='gateway-mvc-1.0.0[.]jar|scripts/Upstream[.]java'
|
||||
for p in $(ps -eo pid,args | grep -E "$pat" | grep -v grep | awk '{print $1}'); do kill "$p" 2>/dev/null; done
|
||||
sleep 2
|
||||
}
|
||||
|
||||
wait_http() { for _ in $(seq 1 60); do curl -s -o /dev/null "$1" && return 0; sleep 1; done; return 1; }
|
||||
|
||||
start_upstream() {
|
||||
setsid nohup java "$HERE/scripts/Upstream.java" 9091 > "$LOGDIR/upstream.log" 2>&1 < /dev/null &
|
||||
wait_http http://localhost:9091/hello
|
||||
}
|
||||
|
||||
# start_gateway <port> [extra spring args...]
|
||||
start_gateway() {
|
||||
local port="$1"; shift
|
||||
setsid nohup java -jar "$JAR" --server.port="$port" "$@" > "$LOGDIR/gateway-$port.log" 2>&1 < /dev/null &
|
||||
wait_http "http://localhost:$port/diag/thread"
|
||||
}
|
||||
|
||||
# show <curl args...> : prints the command, then status line + interesting headers + body
|
||||
show() {
|
||||
echo "\$ curl -i $*"
|
||||
curl -si "$@" | tr -d '\r' | grep -viE '^(date|content-length|connection|keep-alive|transfer-encoding):'
|
||||
echo
|
||||
}
|
||||
Executable
+153
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates every file in output/. Needs: JDK 25, Maven, redis-server on PATH.
|
||||
# ./scripts/run-all.sh
|
||||
# Timing figures (elapsed_ms, curl time) drift a little between runs; everything else is deterministic.
|
||||
set -u
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
OUT="$HERE/output"; mkdir -p "$OUT"
|
||||
cd "$HERE"
|
||||
[ -f "$JAR" ] || mvn -B -q -DskipTests package
|
||||
|
||||
redis_up() { redis-cli ping >/dev/null 2>&1 || { redis-server --port 6379 --save "" --daemonize yes >/dev/null; sleep 1; }; }
|
||||
redis_down() { redis-cli shutdown nosave >/dev/null 2>&1; sleep 1; }
|
||||
redis_up; redis-cli flushall >/dev/null
|
||||
stop_all; start_upstream
|
||||
|
||||
# ---------------------------------------------------------------- 01 routes
|
||||
start_gateway 8080
|
||||
{
|
||||
show localhost:8080/api/hello
|
||||
show localhost:8080/yaml/hello
|
||||
show localhost:8080/diag/thread
|
||||
echo "# what the backend receives by default; note a client-supplied X-Forwarded-For is stripped"
|
||||
echo "\$ curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers"
|
||||
curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers
|
||||
echo
|
||||
} > "$OUT/01-routes.txt"
|
||||
stop_all; start_upstream
|
||||
start_gateway 8080 --spring.cloud.gateway.server.webmvc.trusted-proxies='.*'
|
||||
{
|
||||
echo
|
||||
echo "# same request with spring.cloud.gateway.server.webmvc.trusted-proxies=.*"
|
||||
echo "\$ curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers"
|
||||
curl -s -H 'X-Forwarded-For: 1.2.3.4' localhost:8080/api/headers | grep -iE 'forward|x-gateway'
|
||||
} >> "$OUT/01-routes.txt"
|
||||
stop_all; start_upstream; start_gateway 8080
|
||||
|
||||
# ---------------------------------------------------------------- 02 retry
|
||||
{
|
||||
echo "# the backend fails its first 2 calls with 503; the gateway route retries up to 3 times"
|
||||
show localhost:9091/flaky/reset
|
||||
show 'localhost:8080/api/flaky?failFirst=2'
|
||||
echo "# how many calls did the backend actually see? (failFirst=0 just returns the counter)"
|
||||
show 'localhost:9091/flaky?failFirst=0'
|
||||
echo "# now a backend that never recovers: after the 3 retries the gateway gives up with a 500, not the backend's 503"
|
||||
show localhost:9091/flaky/reset
|
||||
show 'localhost:8080/api/flaky?failFirst=99'
|
||||
echo "# the backend saw the original try plus 3 retries = 4 calls, so the counter now reads 5"
|
||||
show 'localhost:9091/flaky?failFirst=99'
|
||||
echo "# log line behind that 500:"
|
||||
grep -m1 'RetryException' "$LOGDIR/gateway-8080.log" | sed -E 's/^.*(Request processing failed: [^]]*).*$/\1/' | sed -E 's/(RetryException: Retry policy for operation).*/\1 ... (FrameworkRetryFilterFunctions lambda)/'
|
||||
} > "$OUT/02-retry.txt"
|
||||
stop_all; start_upstream
|
||||
start_gateway 8080 --logging.level.org.springframework.cloud.gateway=DEBUG
|
||||
{
|
||||
echo "# which retry implementation did the gateway pick? (DEBUG log at startup)"
|
||||
grep -m1 'Retry filter selection' "$LOGDIR/gateway-8080.log" | sed -E 's/^.*(Retry filter selection)/\1/'
|
||||
} >> "$OUT/02-retry.txt"
|
||||
stop_all; start_upstream
|
||||
|
||||
# ---------------------------------------------------------------- 03 rate limit (Caffeine, single JVM)
|
||||
start_gateway 8080
|
||||
{
|
||||
echo "# 5 tokens per 10 seconds per X-Api-Key, Caffeine store"
|
||||
for i in 1 2 3 4 5 6 7; do
|
||||
printf 'alice #%s ' "$i"; curl -s -o /dev/null -D - -H 'X-Api-Key: alice' localhost:8080/api/limited | tr -d '\r' | grep -iE '^HTTP|x-ratelimit' | tr '\n' ' '; echo
|
||||
done
|
||||
echo "# a different key has its own bucket"
|
||||
printf 'bob #1 '; curl -s -o /dev/null -D - -H 'X-Api-Key: bob' localhost:8080/api/limited | tr -d '\r' | grep -iE '^HTTP|x-ratelimit' | tr '\n' ' '; echo
|
||||
echo "# no X-Api-Key: the key resolver returns null"
|
||||
show localhost:8080/api/limited
|
||||
echo "# wait 11 seconds: the bucket refills"
|
||||
sleep 11
|
||||
printf 'alice #8 '; curl -s -o /dev/null -D - -H 'X-Api-Key: alice' localhost:8080/api/limited | tr -d '\r' | grep -iE '^HTTP|x-ratelimit' | tr '\n' ' '; echo
|
||||
} > "$OUT/03-ratelimit.txt"
|
||||
stop_all; start_upstream
|
||||
|
||||
# ---------------------------------------------------------------- 04 two gateways, one Redis
|
||||
start_gateway 8080 --demo.store=redis
|
||||
start_gateway 8081 --demo.store=redis
|
||||
{
|
||||
echo "# same key, alternating between two gateway instances that share Redis"
|
||||
for i in 1 2 3 4 5 6; do
|
||||
port=$((8080 + (i % 2)))
|
||||
printf 'carol #%s via :%s ' "$i" "$port"; curl -s -o /dev/null -D - -H 'X-Api-Key: carol' localhost:$port/api/limited | tr -d '\r' | grep -iE '^HTTP|x-ratelimit' | tr '\n' ' '; echo
|
||||
done
|
||||
echo "# what Redis holds"
|
||||
echo "\$ redis-cli --scan"; redis-cli --scan
|
||||
echo "\$ redis-cli pttl carol (time to live in ms; the bucket expires once it would be full again)"
|
||||
redis-cli pttl carol | awk '{ if ($1 > 0) print "positive TTL, as expected"; else print $1 }'
|
||||
} > "$OUT/04-shared-redis.txt"
|
||||
stop_all; start_upstream
|
||||
|
||||
# ---------------------------------------------------------------- 05 failure modes
|
||||
{
|
||||
echo "## A. read timeout: spring.http.clients.read-timeout=1s, backend sleeps 3s"
|
||||
start_gateway 8080 --spring.http.clients.read-timeout=1s
|
||||
show 'localhost:8080/api/slow?ms=3000'
|
||||
echo "# log line behind that 500:"
|
||||
grep -m1 'ResourceAccessException' "$LOGDIR/gateway-8080.log" | sed -E 's/^.*(Request processing failed: [^"]*"[^"]*").*$/\1/'
|
||||
echo
|
||||
echo "## B. same timeout, route with onError(ResourceAccessException) mapped to 504"
|
||||
show 'localhost:8080/api/slow-mapped?ms=3000'
|
||||
stop_all; start_upstream
|
||||
|
||||
echo "## C. Redis stops while the gateway is up; no timeout configured on rateLimit()"
|
||||
redis_up
|
||||
start_gateway 8080 --demo.store=redis
|
||||
curl -s -o /dev/null -H 'X-Api-Key: warm' localhost:8080/api/limited # open the Redis connection while it is up
|
||||
redis_down
|
||||
echo "\$ curl --max-time 5 -H 'X-Api-Key: dave' localhost:8080/api/limited"
|
||||
curl -s --max-time 5 -o /dev/null -H 'X-Api-Key: dave' localhost:8080/api/limited -w 'curl exit after %{time_total}s, http_code=%{http_code}\n'
|
||||
stop_all; start_upstream
|
||||
|
||||
echo
|
||||
echo "## D. same outage, with demo.rl-timeout=300ms (setTimeout on the filter)"
|
||||
redis_up
|
||||
start_gateway 8080 --demo.store=redis --demo.rl-timeout=300ms
|
||||
curl -s -o /dev/null -H 'X-Api-Key: warm' localhost:8080/api/limited # open the Redis connection while it is up
|
||||
redis_down
|
||||
echo "\$ curl -H 'X-Api-Key: dave' localhost:8080/api/limited"
|
||||
curl -s -o /dev/null -H 'X-Api-Key: dave' localhost:8080/api/limited -w 'http_code=%{http_code} time_total_under_1s=%{time_total}\n' | sed -E 's/time_total_under_1s=0\.[0-9]+/time_total_under_1s=yes/'
|
||||
echo "# log line behind that 500:"
|
||||
grep -m1 'TimeoutException' "$LOGDIR/gateway-8080.log" | sed -E 's/^.*(Request processing failed: [^]]*).*$/\1/'
|
||||
redis_up
|
||||
echo "# Redis back: the next request works again, no restart needed"
|
||||
curl -s -o /dev/null -H 'X-Api-Key: dave' localhost:8080/api/limited -w 'http_code=%{http_code}\n'
|
||||
stop_all; start_upstream
|
||||
|
||||
echo
|
||||
echo "## E. no AsyncProxyManager bean at all (--demo.store=none)"
|
||||
start_gateway 8080 --demo.store=none
|
||||
echo "\$ curl -i -H 'X-Api-Key: erin' localhost:8080/api/limited"
|
||||
curl -si -H 'X-Api-Key: erin' localhost:8080/api/limited | tr -d '\r' | grep -viE '^(date|content-length|connection|transfer-encoding):'
|
||||
echo
|
||||
echo "# log line behind that 500:"
|
||||
grep -m1 -E 'NoSuchBeanDefinition|AsyncProxyManager' "$LOGDIR/gateway-8080.log" | sed -E 's/^.*(Request processing failed: [^]]*).*$/\1/' | cut -c1-300
|
||||
} 2>&1 | grep -v "^Picked up " > "$OUT/05-failure-modes.txt"
|
||||
stop_all; start_upstream
|
||||
|
||||
# ---------------------------------------------------------------- 06 virtual vs platform threads
|
||||
{
|
||||
for mode in virtual platform; do
|
||||
if [ "$mode" = virtual ]; then start_gateway 8080; else start_gateway 8080 --spring.profiles.active=platform; fi
|
||||
echo "## $mode threads (server.tomcat.threads.max=10)"
|
||||
show localhost:8080/diag/thread | sed -E 's/#[0-9]+/#N/'
|
||||
echo "\$ java scripts/LoadClient.java 'http://localhost:8080/api/slow?ms=500' 200"
|
||||
java scripts/LoadClient.java 'http://localhost:8080/api/slow?ms=500' 200
|
||||
echo
|
||||
stop_all; start_upstream
|
||||
done
|
||||
} 2>&1 | grep -v "^Picked up " > "$OUT/06-virtual-threads.txt"
|
||||
stop_all
|
||||
echo "done: $(ls "$OUT" | wc -l) files in $OUT"
|
||||
Reference in New Issue
Block a user