Add openfeign-demo: OpenFeign vs @HttpExchange on Spring Boot 4.2.0 + Spring Cloud 2026.0.0

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b3W3uHbHAmM3orhn7b
This commit is contained in:
Ankur
2026-11-26 00:46:05 +05:30
co-authored by Claude Sonnet 5.5
parent def73fa1c4
commit 7211b0fb80
43 changed files with 927 additions and 0 deletions
@@ -0,0 +1,16 @@
package com.ankurm.feign;
import com.ankurm.feign.client.HttpStudentClient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.web.service.registry.ImportHttpServices;
@SpringBootApplication
@EnableFeignClients // scans for @FeignClient interfaces
@ImportHttpServices(group = "students", types = HttpStudentClient.class) // the @HttpExchange alternative
public class FeignDemoApplication {
public static void main(String[] args) {
SpringApplication.run(FeignDemoApplication.class, args);
}
}
@@ -0,0 +1,4 @@
package com.ankurm.feign;
/** The payload shared by the fake remote service and every client. */
public record Student(int id, String name, String branch) {}
@@ -0,0 +1,14 @@
package com.ankurm.feign.client;
import com.ankurm.feign.Student;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/** Same call as StudentClient, but with a custom ErrorDecoder and a fixed URL instead of a service ID. */
@FeignClient(name = "decoded", url = "${demo.remote-url}", configuration = DomainErrorConfig.class)
public interface DecodedStudentClient {
@GetMapping("/api/students/{id}")
Student findById(@PathVariable("id") int id);
}
@@ -0,0 +1,20 @@
package com.ankurm.feign.client;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.springframework.context.annotation.Bean;
/** Per-client configuration. Deliberately NOT annotated @Configuration (see the pitfalls in the post). */
public class DomainErrorConfig {
@Bean
ErrorDecoder domainErrorDecoder() {
ErrorDecoder fallbackToDefault = new ErrorDecoder.Default();
return (methodKey, response) -> {
if (response.status() == 404) {
return new StudentNotFoundException("404 from " + methodKey + " (" + response.request().url() + ")");
}
return fallbackToDefault.decode(methodKey, response);
};
}
}
@@ -0,0 +1,23 @@
package com.ankurm.feign.client;
import com.ankurm.feign.Student;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.service.annotation.GetExchange;
import org.springframework.web.service.annotation.HttpExchange;
import org.springframework.web.service.annotation.PostExchange;
/** The same contract as StudentClient, as a Spring HTTP interface: no extra starter, RestClient underneath. */
@HttpExchange("/api/students")
public interface HttpStudentClient {
@GetExchange
List<Student> findAll();
@GetExchange("/{id}")
Student findById(@PathVariable("id") int id);
@PostExchange
Student create(@RequestBody Student student);
}
@@ -0,0 +1,13 @@
package com.ankurm.feign.client;
import com.ankurm.feign.Student;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
/** Identical to RetryingStudentClient but with no Retryer bean: the Spring Cloud default. */
@FeignClient(name = "noretry", url = "${demo.remote-url}")
public interface NoRetryStudentClient {
@GetMapping("/api/students/flaky/{key}")
Student flakyGet(@PathVariable("key") String key, @RequestParam("failures") int failures);
}
@@ -0,0 +1,15 @@
package com.ankurm.feign.client;
import com.ankurm.feign.Student;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@FeignClient(name = "resilient", url = "${demo.remote-url}", fallback = StudentClientFallback.class)
public interface ResilientStudentClient {
@GetMapping("/api/students/{id}")
Student findById(@PathVariable("id") int id);
@PostMapping("/api/students/orders/{key}")
Student placeOrder(@PathVariable("key") String key, @RequestParam("failures") int failures);
}
@@ -0,0 +1,12 @@
package com.ankurm.feign.client;
import feign.Retryer;
import org.springframework.context.annotation.Bean;
public class RetryConfig {
@Bean
Retryer retryer() {
return new Retryer.Default(50, 200, 3); // period 50 ms, max period 200 ms, at most 3 attempts
}
}
@@ -0,0 +1,15 @@
package com.ankurm.feign.client;
import com.ankurm.feign.Student;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
@FeignClient(name = "retrying", url = "${demo.remote-url}", configuration = RetryConfig.class)
public interface RetryingStudentClient {
@GetMapping("/api/students/flaky/{key}")
Student flakyGet(@PathVariable("key") String key, @RequestParam("failures") int failures);
@PostMapping("/api/students/orders/{key}")
Student flakyPost(@PathVariable("key") String key, @RequestParam("failures") int failures);
}
@@ -0,0 +1,23 @@
package com.ankurm.feign.client;
import com.ankurm.feign.Student;
import java.util.List;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;
/** The plain OpenFeign client. "student-service" is a service ID, resolved by Spring Cloud LoadBalancer. */
@FeignClient(name = "student-service")
public interface StudentClient {
@GetMapping("/api/students")
List<Student> findAll();
@GetMapping("/api/students/{id}")
Student findById(@PathVariable("id") int id); // ALWAYS name the variable
@PostMapping("/api/students")
Student create(@RequestBody Student student);
@GetMapping("/api/students/slow")
String slow(@RequestParam("ms") int ms);
}
@@ -0,0 +1,19 @@
package com.ankurm.feign.client;
import com.ankurm.feign.Student;
import org.springframework.stereotype.Component;
/** Reads degrade to a placeholder. Writes must NOT pretend to succeed. */
@Component
class StudentClientFallback implements ResilientStudentClient {
@Override
public Student findById(int id) {
return new Student(id, "unknown", "unknown");
}
@Override
public Student placeOrder(String key, int failures) {
throw new IllegalStateException("student-service down; order " + key + " not placed");
}
}
@@ -0,0 +1,7 @@
package com.ankurm.feign.client;
public class StudentNotFoundException extends RuntimeException {
public StudentNotFoundException(String message) {
super(message);
}
}
@@ -0,0 +1,14 @@
package com.ankurm.feign.client;
import com.ankurm.feign.Student;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/** Deliberately breaks the rule above: no name in @PathVariable. Works only if compiled with -parameters. */
@FeignClient(name = "unnamed", url = "${demo.remote-url}")
public interface UnnamedPathVariableClient {
@GetMapping("/api/students/{id}")
Student byId(@PathVariable int id);
}
@@ -0,0 +1,75 @@
package com.ankurm.feign.remote;
import com.ankurm.feign.Student;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
/**
* The "downstream service" every client in this module calls. It lives in the same JVM only so the
* demo is one command; the clients reach it over real HTTP on localhost.
*/
@RestController
@RequestMapping("/api/students")
public class RemoteStudentController {
private final AtomicInteger nextId = new AtomicInteger(100);
private final Map<String, AtomicInteger> calls = new ConcurrentHashMap<>();
@GetMapping
public List<Student> findAll() {
return List.of(new Student(1, "Asha", "CS"), new Student(2, "Ravi", "IT"), new Student(3, "Meera", "EXTC"));
}
@GetMapping("/{id}")
public ResponseEntity<?> findById(@PathVariable int id) {
if (id == 99) {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, "No student with id 99");
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(pd);
}
if (id == 503) {
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build();
}
return ResponseEntity.ok(new Student(id, "Student-" + id, "CS"));
}
@PostMapping
public ResponseEntity<Student> create(@RequestBody Student s) {
return ResponseEntity.status(HttpStatus.CREATED).body(new Student(nextId.getAndIncrement(), s.name(), s.branch()));
}
/** Sleeps, then answers. Used to trigger read timeouts. */
@GetMapping(value = "/slow", produces = "text/plain")
public String slow(@RequestParam("ms") int ms) throws InterruptedException {
Thread.sleep(ms);
return "answered after " + ms + " ms";
}
/** Answers 503 + Retry-After: 0 for the first {@code failures} calls per key, then succeeds. */
@GetMapping("/flaky/{key}")
public ResponseEntity<?> flaky(@PathVariable String key, @RequestParam("failures") int failures) {
int n = calls.computeIfAbsent(key, k -> new AtomicInteger()).incrementAndGet();
if (n <= failures) {
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).header(HttpHeaders.RETRY_AFTER, "0").build();
}
return ResponseEntity.ok(new Student(n, "flaky-" + key, "CS"));
}
/** How many times /flaky/{key} was called. */
@GetMapping(value = "/calls/{key}", produces = "text/plain")
public String calls(@PathVariable String key) {
return String.valueOf(calls.getOrDefault(key, new AtomicInteger()).get());
}
/** Counts POSTs that reach the server, to expose retried writes. */
@PostMapping("/orders/{key}")
public ResponseEntity<?> order(@PathVariable String key, @RequestParam("failures") int failures) {
return flaky(key, failures);
}
}
@@ -0,0 +1,5 @@
spring:
cloud:
openfeign:
circuitbreaker:
enabled: true
@@ -0,0 +1,7 @@
spring:
cloud:
openfeign:
client:
config:
student-service: # per-client override
read-timeout: 1000
@@ -0,0 +1,6 @@
# The 2020-era prefix. It does not bind on current releases.
feign:
client:
config:
student-service:
read-timeout: 1000
@@ -0,0 +1,30 @@
server:
port: 18367
demo:
remote-url: http://localhost:18367
spring:
application:
name: openfeign-demo
cloud:
discovery:
client:
simple:
instances:
student-service:
- uri: http://localhost:18367 # stands in for Eureka: "student-service" -> this URI
openfeign:
client:
config:
default: # applies to every client
connect-timeout: 2000
logger-level: basic
http:
serviceclient:
students:
base-url: http://localhost:18367
logging:
level:
com.ankurm.feign.client.StudentClient: DEBUG # Feign logs under the interface name
@@ -0,0 +1,49 @@
package com.ankurm.feign;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import com.ankurm.feign.client.DecodedStudentClient;
import com.ankurm.feign.client.StudentClient;
import com.ankurm.feign.client.StudentNotFoundException;
import feign.FeignException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class ErrorHandlingTest {
@Autowired StudentClient plain;
@Autowired DecodedStudentClient decoded;
@Test
void defaultVersusCustomErrorDecoder() throws Exception {
Transcript t = new Transcript("02-error-handling.txt");
Throwable defaultFailure = org.assertj.core.api.Assertions.catchThrowable(() -> plain.findById(99));
t.line("StudentClient.findById(99) [default decoder]");
t.line(" exception : %s", defaultFailure.getClass().getName());
t.line(" status : %d", ((FeignException) defaultFailure).status());
t.line(" message : %s", defaultFailure.getMessage().lines().findFirst().orElse(""));
t.line("");
Throwable decodedFailure = org.assertj.core.api.Assertions.catchThrowable(() -> decoded.findById(99));
t.line("DecodedStudentClient.findById(99) [custom ErrorDecoder]");
t.line(" exception : %s", decodedFailure.getClass().getName());
t.line(" message : %s", decodedFailure.getMessage());
t.line("");
Throwable unavailable = org.assertj.core.api.Assertions.catchThrowable(() -> decoded.findById(503));
t.line("DecodedStudentClient.findById(503) [custom decoder delegates non-404 to the default]");
t.line(" exception : %s", unavailable.getClass().getName());
t.line(" status : %d", ((FeignException) unavailable).status());
t.write();
assertThat(defaultFailure).isInstanceOf(FeignException.NotFound.class);
assertThatThrownBy(() -> decoded.findById(99)).isInstanceOf(StudentNotFoundException.class);
assertThat(unavailable).isInstanceOf(FeignException.ServiceUnavailable.class);
}
}
@@ -0,0 +1,46 @@
package com.ankurm.feign;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import com.ankurm.feign.client.ResilientStudentClient;
import com.ankurm.feign.client.StudentClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ActiveProfiles("fallback")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class FallbackTest {
@Autowired ResilientStudentClient client;
@Autowired StudentClient plainButNowWrapped;
@Test
void fallbacksAndTheOneSecondTrap() throws Exception {
Transcript t = new Transcript("06-fallback.txt");
Student read = client.findById(503);
t.line("findById(503), server answers 503 -> %s", read);
Throwable write = catchThrowable(() -> client.placeOrder("w", 5));
t.line("placeOrder(w), server answers 503 -> %s: %s", write.getClass().getSimpleName(), write.getMessage());
// circuitbreaker.enabled=true wraps EVERY Feign client, including ones with no fallback.
long start = System.nanoTime();
Throwable slow = catchThrowable(() -> plainButNowWrapped.slow(3000));
long ms = (System.nanoTime() - start) / 1_000_000;
t.line("");
t.line("StudentClient.slow(3000) with circuitbreaker.enabled=true and NO read-timeout configured:");
t.line(" threw %s after about %d ms", slow.getClass().getName(), (ms / 100) * 100);
t.line(" message: %s", slow.getMessage());
t.line(" cause : %s", slow.getCause() == null ? "none" : slow.getCause().getClass().getName());
t.write();
assertThat(read.name()).isEqualTo("unknown");
assertThat(write).isInstanceOf(IllegalStateException.class);
}
}
@@ -0,0 +1,45 @@
package com.ankurm.feign;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.feign.client.StudentClient;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.test.annotation.DirtiesContext;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ExtendWith(OutputCaptureExtension.class)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class HappyPathTest {
@Autowired StudentClient client;
@Test
void callsTheRemoteServiceThroughAServiceId(CapturedOutput out) throws Exception {
Transcript t = new Transcript("01-happy-path.txt");
List<Student> all = client.findAll();
Student one = client.findById(2);
Student created = client.create(new Student(0, "Kiran", "ME"));
t.line("findAll() -> %s", all);
t.line("findById(2) -> %s", one);
t.line("create(Kiran, ME) -> %s", created);
t.line("");
t.line("Feign's own log (logger-level: basic):");
out.getOut().lines()
.filter(l -> l.contains("StudentClient#"))
.map(l -> l.substring(l.indexOf("[StudentClient#")))
.forEach(l -> t.line("%s", l));
t.write();
assertThat(all).hasSize(3);
assertThat(one).isEqualTo(new Student(2, "Student-2", "CS"));
assertThat(created.id()).isGreaterThanOrEqualTo(100);
}
}
@@ -0,0 +1,31 @@
package com.ankurm.feign;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import com.ankurm.feign.client.HttpStudentClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.web.client.HttpClientErrorException;
/** Same client, with Spring Cloud's HTTP-service circuit breaker switched off. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = "spring.cloud.circuitbreaker.http-services.enabled=false")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class HttpInterfacePlainTest {
@Autowired HttpStudentClient client;
@Test
void errorsComeBackAsRestClientExceptions() throws Exception {
Transcript t = new Transcript("08-http-interface-plain-errors.txt");
Throwable nf = catchThrowable(() -> client.findById(99));
t.line("findById(99) with spring.cloud.circuitbreaker.http-services.enabled=false:");
t.line(" exception : %s", nf.getClass().getName());
t.line(" message : %s", nf.getMessage());
t.write();
assertThat(nf).isInstanceOf(HttpClientErrorException.NotFound.class);
}
}
@@ -0,0 +1,44 @@
package com.ankurm.feign;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import com.ankurm.feign.client.HttpStudentClient;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.web.client.HttpClientErrorException;
/** The resilience4j starter is on the classpath, so Spring Cloud wraps every @HttpExchange group by default. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class HttpInterfaceTest {
@Autowired HttpStudentClient client;
@Test
void sameContractWithoutFeign() throws Exception {
Transcript t = new Transcript("07-http-interface.txt");
List<Student> all = client.findAll();
Student one = client.findById(2);
Student created = client.create(new Student(0, "Kiran", "ME"));
t.line("findAll() -> %s", all);
t.line("findById(2) -> %s", one);
t.line("create(Kiran, ME) -> %s", created);
Throwable nf = catchThrowable(() -> client.findById(99));
t.line("");
t.line("findById(99), circuit breaker starter on the classpath (default):");
t.line(" exception : %s", nf.getClass().getName());
t.line(" message : %s", nf.getMessage());
t.line(" cause : %s", nf.getCause() == null ? "none" : nf.getCause().getClass().getName());
t.write();
assertThat(all).hasSize(3);
assertThat(nf).isInstanceOf(NoFallbackAvailableException.class);
assertThat(nf.getCause()).isInstanceOf(HttpClientErrorException.NotFound.class);
}
}
@@ -0,0 +1,53 @@
package com.ankurm.feign;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import com.ankurm.feign.client.NoRetryStudentClient;
import com.ankurm.feign.client.RetryingStudentClient;
import feign.FeignException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.web.client.RestClient;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class RetryTest {
@Autowired NoRetryStudentClient noRetry;
@Autowired RetryingStudentClient retrying;
private int serverCalls(String key) {
String n = RestClient.create("http://localhost:18367").get().uri("/api/students/calls/{k}", key)
.retrieve().body(String.class);
return Integer.parseInt(n);
}
@Test
void retryerBeanDecidesWhetherA503IsRetried() throws Exception {
Transcript t = new Transcript("05-retries.txt");
t.line("Server answers 503 + 'Retry-After: 0' for the first 2 calls, then 200.");
t.line("");
Throwable a = catchThrowable(() -> noRetry.flakyGet("a", 2));
t.line("no Retryer bean (the default) : %s, server saw %d call(s)", a == null ? "success" : a.getClass().getSimpleName(), serverCalls("a"));
Student b = retrying.flakyGet("b", 2);
t.line("Retryer.Default(50,200,3) GET : success %s, server saw %d call(s)", b, serverCalls("b"));
Throwable c = catchThrowable(() -> retrying.flakyGet("c", 5));
t.line("same Retryer, server keeps 503 : %s, server saw %d call(s)", c.getClass().getSimpleName(), serverCalls("c"));
Student d = retrying.flakyPost("d", 2);
t.line("same Retryer on a POST : success %s, server saw %d call(s) for ONE client call", d, serverCalls("d"));
t.write();
assertThat(a).isInstanceOf(feign.RetryableException.class);
assertThat(serverCalls("a")).isEqualTo(1);
assertThat(serverCalls("b")).isEqualTo(3);
assertThat(serverCalls("c")).isEqualTo(3);
assertThat(serverCalls("d")).isEqualTo(3);
}
}
@@ -0,0 +1,38 @@
package com.ankurm.feign;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.feign.client.StudentClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
/** The server sleeps 3000 ms; the configured read-timeout is 1000 ms - if the property binds. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ActiveProfiles("newprefix")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class TimeoutNewPrefixTest {
@Autowired StudentClient client;
@Test
void slowCall() throws Exception {
Transcript t = new Transcript("03-timeout-newprefix.txt");
long start = System.nanoTime();
String outcome;
try {
outcome = "returned: " + client.slow(3000);
} catch (Exception e) {
outcome = "threw " + e.getClass().getName() + " -> " + e.getMessage().lines().findFirst().orElse("");
}
long ms = (System.nanoTime() - start) / 1_000_000;
t.line("profile : newprefix");
t.line("server sleeps: 3000 ms, read-timeout configured: 1000 ms");
t.line("outcome : %s", outcome);
t.line("took : %s", ms >= 2900 ? "about 3000 ms (waited for the full answer)" : "about 1000 ms (gave up at the timeout)");
t.write();
assertThat(outcome).startsWith("threw");
}
}
@@ -0,0 +1,38 @@
package com.ankurm.feign;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.feign.client.StudentClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
/** The server sleeps 3000 ms; the configured read-timeout is 1000 ms - if the property binds. */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@ActiveProfiles("oldprefix")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class TimeoutOldPrefixTest {
@Autowired StudentClient client;
@Test
void slowCall() throws Exception {
Transcript t = new Transcript("04-timeout-oldprefix.txt");
long start = System.nanoTime();
String outcome;
try {
outcome = "returned: " + client.slow(3000);
} catch (Exception e) {
outcome = "threw " + e.getClass().getName() + " -> " + e.getMessage().lines().findFirst().orElse("");
}
long ms = (System.nanoTime() - start) / 1_000_000;
t.line("profile : oldprefix");
t.line("server sleeps: 3000 ms, read-timeout configured: 1000 ms");
t.line("outcome : %s", outcome);
t.line("took : %s", ms >= 2900 ? "about 3000 ms (waited for the full answer)" : "about 1000 ms (gave up at the timeout)");
t.write();
assertThat(outcome).startsWith("returned");
}
}
@@ -0,0 +1,24 @@
package com.ankurm.feign;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/** Collects lines while a test runs and writes them to output/NN-name.txt, so the post quotes real runs. */
final class Transcript {
private final Path file;
private final StringBuilder text = new StringBuilder();
Transcript(String name) {
this.file = Path.of("output", name);
}
void line(String format, Object... args) {
text.append(String.format(format, args)).append('\n');
}
void write() throws IOException {
Files.createDirectories(file.getParent());
Files.writeString(file, text.toString());
}
}
@@ -0,0 +1,25 @@
package com.ankurm.feign;
import static org.assertj.core.api.Assertions.assertThat;
import com.ankurm.feign.client.UnnamedPathVariableClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
/**
* Passes in a normal build (the Boot parent compiles with -parameters).
* scripts/no-parameters.sh runs it with -Pnoparams and captures the failure.
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class UnnamedPathVariableTest {
@Autowired UnnamedPathVariableClient client;
@Test
void unnamedPathVariableNeedsParametersFlag() {
assertThat(client.byId(7).id()).isEqualTo(7);
}
}