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:
co-authored by
Claude Sonnet 5.5
parent
def73fa1c4
commit
7211b0fb80
@@ -19,6 +19,7 @@ discovery-server :8761 (Eureka) every service registers here and finds the othe
|
||||
| `gateway` | Spring Cloud Gateway Server WebMVC; routes come from the config server (`gateway.yml`) |
|
||||
| `product-service` | `GET /products`, `GET /products/{id}` |
|
||||
| `inventory-service` | stock levels, `POST /inventory/{id}/reserve`, a switch to simulate an outage |
|
||||
| `openfeign-demo` | standalone, **not** part of the build above: OpenFeign vs `@HttpExchange` on Boot 4.2.0 / Cloud 2026.0.0; see its own README |
|
||||
| `order-service` | `POST /orders`; calls product-service and inventory-service through the load balancer and a Resilience4j circuit breaker |
|
||||
|
||||
## Run it (no Docker needed)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
target/
|
||||
@@ -0,0 +1,39 @@
|
||||
# openfeign-demo
|
||||
|
||||
Declarative REST clients on **Spring Boot 4.2.0 + Spring Cloud 2026.0.0 (OpenFeign 5.1.0, Feign 13.17)**, written for
|
||||
[Spring Cloud OpenFeign on Spring Boot 4: Declarative REST Clients](https://ankurm.com/spring-cloud-creating-rest-client-using-feign/).
|
||||
Standalone module with its own parent; the rest of this repository stays on Boot 4.1.1 / Cloud 2025.1.3.
|
||||
|
||||
A fake "student service" runs in the same JVM (`remote/RemoteStudentController`); every client reaches it over real HTTP on `localhost:18367`.
|
||||
|
||||
| Package / file | What it shows |
|
||||
|---|---|
|
||||
| `client/StudentClient` | OpenFeign client addressed by service ID (`student-service`) |
|
||||
| `client/DecodedStudentClient` + `DomainErrorConfig` | custom `ErrorDecoder`, fixed `url` |
|
||||
| `client/RetryingStudentClient` + `RetryConfig` / `NoRetryStudentClient` | `Retryer` bean on and off |
|
||||
| `client/ResilientStudentClient` + `StudentClientFallback` | fallbacks through Spring Cloud CircuitBreaker |
|
||||
| `client/UnnamedPathVariableClient` | the `@PathVariable` without a name trap |
|
||||
| `client/HttpStudentClient` | the same contract as a Spring `@HttpExchange` interface |
|
||||
| `application-*.yml` | `newprefix` / `oldprefix` (timeouts), `fallback` (circuit breaker on) |
|
||||
|
||||
## Run
|
||||
|
||||
Needs JDK 25 (set `java.version` in `pom.xml` to 21 for older JDKs) and Maven 3.9+.
|
||||
|
||||
```bash
|
||||
./scripts/run-all.sh # tests (they write output/01..08) + scripts/no-parameters.sh (writes output/09)
|
||||
```
|
||||
|
||||
## Captured output
|
||||
|
||||
Written by the tests themselves; the assertions fail the build if a number stops being true. Timings in the Feign log lines drift between runs.
|
||||
|
||||
| File | Shows |
|
||||
|---|---|
|
||||
| `01-happy-path.txt` | calls through a service ID, plus Feign's own log lines |
|
||||
| `02-error-handling.txt` | default `FeignException.NotFound` vs a custom `ErrorDecoder` |
|
||||
| `03-timeout-newprefix.txt` / `04-timeout-oldprefix.txt` | `spring.cloud.openfeign.client.config.*` vs the 2020-era `feign.client.config.*` |
|
||||
| `05-retries.txt` | which calls are retried, and the POST that was sent three times |
|
||||
| `06-fallback.txt` | fallbacks, and the one-second time limit that appears with `circuitbreaker.enabled=true` |
|
||||
| `07-http-interface.txt` / `08-http-interface-plain-errors.txt` | `@HttpExchange`, with and without Spring Cloud's circuit-breaker wrapper |
|
||||
| `09-no-parameters.txt` | `PathVariable annotation was empty on param 0` when compiled without `-parameters` |
|
||||
@@ -0,0 +1,11 @@
|
||||
findAll() -> [Student[id=1, name=Asha, branch=CS], Student[id=2, name=Ravi, branch=IT], Student[id=3, name=Meera, branch=EXTC]]
|
||||
findById(2) -> Student[id=2, name=Student-2, branch=CS]
|
||||
create(Kiran, ME) -> Student[id=100, name=Kiran, branch=ME]
|
||||
|
||||
Feign's own log (logger-level: basic):
|
||||
[StudentClient#findAll] ---> GET http://student-service/api/students HTTP/1.1
|
||||
[StudentClient#findAll] <--- HTTP/1.1 200 (138ms)
|
||||
[StudentClient#findById] ---> GET http://student-service/api/students/2 HTTP/1.1
|
||||
[StudentClient#findById] <--- HTTP/1.1 200 (7ms)
|
||||
[StudentClient#create] ---> POST http://student-service/api/students HTTP/1.1
|
||||
[StudentClient#create] <--- HTTP/1.1 201 (6ms)
|
||||
@@ -0,0 +1,12 @@
|
||||
StudentClient.findById(99) [default decoder]
|
||||
exception : feign.FeignException$NotFound
|
||||
status : 404
|
||||
message : [404] during [GET] to [http://student-service/api/students/99] [StudentClient#findById(int)]: [{"detail":"No student with id 99","status":404,"title":"Not Found"}]
|
||||
|
||||
DecodedStudentClient.findById(99) [custom ErrorDecoder]
|
||||
exception : com.ankurm.feign.client.StudentNotFoundException
|
||||
message : 404 from DecodedStudentClient#findById(int) (http://localhost:18367/api/students/99)
|
||||
|
||||
DecodedStudentClient.findById(503) [custom decoder delegates non-404 to the default]
|
||||
exception : feign.FeignException$ServiceUnavailable
|
||||
status : 503
|
||||
@@ -0,0 +1,4 @@
|
||||
profile : newprefix
|
||||
server sleeps: 3000 ms, read-timeout configured: 1000 ms
|
||||
outcome : threw feign.RetryableException -> Read timed out executing GET http://student-service/api/students/slow?ms=3000
|
||||
took : about 1000 ms (gave up at the timeout)
|
||||
@@ -0,0 +1,4 @@
|
||||
profile : oldprefix
|
||||
server sleeps: 3000 ms, read-timeout configured: 1000 ms
|
||||
outcome : returned: answered after 3000 ms
|
||||
took : about 3000 ms (waited for the full answer)
|
||||
@@ -0,0 +1,6 @@
|
||||
Server answers 503 + 'Retry-After: 0' for the first 2 calls, then 200.
|
||||
|
||||
no Retryer bean (the default) : RetryableException, server saw 1 call(s)
|
||||
Retryer.Default(50,200,3) GET : success Student[id=3, name=flaky-b, branch=CS], server saw 3 call(s)
|
||||
same Retryer, server keeps 503 : RetryableException, server saw 3 call(s)
|
||||
same Retryer on a POST : success Student[id=3, name=flaky-d, branch=CS], server saw 3 call(s) for ONE client call
|
||||
@@ -0,0 +1,7 @@
|
||||
findById(503), server answers 503 -> Student[id=503, name=unknown, branch=unknown]
|
||||
placeOrder(w), server answers 503 -> IllegalStateException: student-service down; order w not placed
|
||||
|
||||
StudentClient.slow(3000) with circuitbreaker.enabled=true and NO read-timeout configured:
|
||||
threw org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException after about 1000 ms
|
||||
message: No fallback available.
|
||||
cause : java.util.concurrent.TimeoutException
|
||||
@@ -0,0 +1,8 @@
|
||||
findAll() -> [Student[id=1, name=Asha, branch=CS], Student[id=2, name=Ravi, branch=IT], Student[id=3, name=Meera, branch=EXTC]]
|
||||
findById(2) -> Student[id=2, name=Student-2, branch=CS]
|
||||
create(Kiran, ME) -> Student[id=100, name=Kiran, branch=ME]
|
||||
|
||||
findById(99), circuit breaker starter on the classpath (default):
|
||||
exception : org.springframework.cloud.client.circuitbreaker.NoFallbackAvailableException
|
||||
message : No fallback available.
|
||||
cause : org.springframework.web.client.HttpClientErrorException$NotFound
|
||||
@@ -0,0 +1,3 @@
|
||||
findById(99) with spring.cloud.circuitbreaker.http-services.enabled=false:
|
||||
exception : org.springframework.web.client.HttpClientErrorException$NotFound
|
||||
message : 404 Not Found: "{"detail":"No student with id 99","status":404,"title":"Not Found"}"
|
||||
@@ -0,0 +1,6 @@
|
||||
mvn -Pnoparams -Dtest=UnnamedPathVariableTest test (maven-compiler-plugin <parameters>false</parameters>)
|
||||
|
||||
Caused by: java.lang.IllegalStateException: PathVariable annotation was empty on param 0.
|
||||
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.ankurm.feign.client.UnnamedPathVariableClient': FactoryBean threw exception on object creation
|
||||
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
|
||||
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 7.498 s <<< FAILURE! -- in com.ankurm.feign.UnnamedPathVariableTest
|
||||
@@ -0,0 +1,91 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<!-- Standalone module: its own parent, newer than the rest of this repository (Boot 4.1.1 / Cloud 2025.1.3). -->
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.2.0</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<groupId>com.ankurm.shop</groupId>
|
||||
<artifactId>openfeign-demo</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>openfeign-demo</name>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<spring-cloud.version>2026.0.0</spring-cloud.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>${spring-cloud.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webmvc</artifactId>
|
||||
</dependency>
|
||||
<!-- Boot 4: spring.http.serviceclient.* (base-url etc.) is applied by this module, not by starter-webmvc -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-restclient</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
</dependency>
|
||||
<!-- resolves service IDs such as "student-service" -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<!-- Compile WITHOUT -parameters, to reproduce the unnamed @PathVariable failure. -->
|
||||
<profile>
|
||||
<id>noparams</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<parameters>false</parameters>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
</project>
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Reproduces the unnamed @PathVariable failure: compile WITHOUT -parameters and run the test that
|
||||
# calls UnnamedPathVariableClient. Writes the real failure to output/09-no-parameters.txt.
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
OUT=output/09-no-parameters.txt
|
||||
mvn -B -Pnoparams clean test -Dtest=UnnamedPathVariableTest test > /tmp/noparams.log 2>&1
|
||||
{
|
||||
echo "mvn -Pnoparams -Dtest=UnnamedPathVariableTest test (maven-compiler-plugin <parameters>false</parameters>)"
|
||||
echo
|
||||
grep -E 'Tests run:.*Fail|IllegalStateException|PathVariable annotation was empty|Caused by' /tmp/noparams.log \
|
||||
| sed -E 's/^\[ERROR\] +//' | sort -u | head -12
|
||||
} > "$OUT"
|
||||
cat "$OUT"
|
||||
mvn -B -q clean test-compile > /dev/null 2>&1 # restore normal (-parameters) classes
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates every file in output/. The tests write output/01..08; the script writes 09.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
rm -f output/*.txt
|
||||
mvn -B -q test
|
||||
./scripts/no-parameters.sh
|
||||
ls output
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user