Installatiegids voor OpenFeign

Configuratie van projectafhankelijkheden

Maven-afhankelijkheden

<!-- Spring Cloud OpenFeign Starter -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

<!-- Required for load balancing support -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

Gradle-afhankelijkheden

implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
implementation 'org.springframework.cloud:spring-cloud-starter-loadbalancer'

Beheer van versies

Gebruik de Spring Cloud BOM om versies in pom.xml te beheren:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>2022.0.4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Basisconfiguratie

Feign-clients inschakelen

Voeg de annotatie @EnableFeignClients toe aan je-hoofdtoepassingsklasse:

@SpringBootApplication
@EnableFeignClients
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Scanpakketten voor clients opgeven

Als je Feign-clientinterfaces niet in hetzelfde pakket als je hoofdklasse staan, geef dan scanpakketten op:

@SpringBootApplication
@EnableFeignClients(basePackages = "com.example.clients")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Of geef clients expliciet op:

@SpringBootApplication
@EnableFeignClients(clients = {UserServiceClient.class, OrderServiceClient.class})
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Feign-clients maken

Basisgebruik

@FeignClient(name = "user-service")
public interface UserService {
    
    @GetMapping("/users/{id}")
    User getUser(@PathVariable("id") Long id);
    
    @GetMapping("/users")
    List<User> getAllUsers();
    
    @PostMapping("/users")
    User createUser(@RequestBody User user);
    
    @PutMapping("/users/{id}")
    User updateUser(@PathVariable("id") Long id, @RequestBody User user);
    
    @DeleteMapping("/users/{id}")
    void deleteUser(@PathVariable("id") Long id);
}

Het URL-attribuut gebruiken

Als je geen servicediscovery nodig hebt, geef dan rechtstreeks een URL op:

@FeignClient(name = "external-api", url = "https://api.example.com")
public interface ExternalApiClient {
    @GetMapping("/data")
    ApiResponse getData();
}

Ondersteunde annotaties

OpenFeign ondersteunt de volgende Spring MVC-annotaties:

  • HTTP-methodeannotaties: @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping
  • Padvariabelen: @PathVariable
  • Verzoekparameters: @RequestParam
  • Requestbody: @RequestBody
  • Verzoekheaders: @RequestHeader
  • Cookies: @CookieValue

Voorbeelden met complexe parameters

@FeignClient(name = "order-service")
public interface OrderService {
    
    // Path variable + request parameter
    @GetMapping("/orders/{userId}")
    List<Order> getOrdersByUser(
        @PathVariable("userId") Long userId,
        @RequestParam("status") String status,
        @RequestParam(value = "page", defaultValue = "0") int page
    );
    
    // Request body + request header
    @PostMapping("/orders")
    @Headers("X-API-Version: 2.0")
    Order createOrder(
        @RequestBody CreateOrderRequest request,
        @RequestHeader("Authorization") String token
    );
    
    // Query parameter Map
    @GetMapping("/orders/search")
    List<Order> searchOrders(@SpringQueryMap SearchCriteria criteria);
}

Feign-clients gebruiken

Injecteren in een service

@Service
public class OrderProcessingService {
    
    private final UserService userService;
    private final OrderService orderService;
    
    public OrderProcessingService(UserService userService, OrderService orderService) {
        this.userService = userService;
        this.orderService = orderService;
    }
    
    public Order processOrder(Long userId, CreateOrderRequest request) {
        // Validate user
        User user = userService.getUser(userId);
        if (user == null) {
            throw new UserNotFoundException("User not found: " + userId);
        }
        
        // Create order
        return orderService.createOrder(request, "Bearer " + generateToken());
    }
    
    private String generateToken() {
        // Generate authentication token
        return "token";
    }
}

Gebruiken in een controller

@RestController
@RequestMapping("/api/v1")
public class OrderController {
    
    private final OrderService orderService;
    
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }
    
    @GetMapping("/orders/{id}")
    public ResponseEntity<Order> getOrder(@PathVariable Long id) {
        Order order = orderService.getOrder(id);
        return ResponseEntity.ok(order);
    }
    
    @PostMapping("/orders")
    public ResponseEntity<Order> createOrder(@RequestBody CreateOrderRequest request) {
        Order order = orderService.createOrder(request);
        return ResponseEntity.status(HttpStatus.CREATED).body(order);
    }
}

Configuratie-eigenschappen

Basisconfiguratie

Configureer in application.yml:

spring:
  cloud:
    openfeign:
      client:
        config:
          default:
            connect-timeout: 5000
            read-timeout: 5000
            logger-level: basic
          user-service:
            connect-timeout: 3000
            read-timeout: 10000
            logger-level: full

Configuratie van logniveaus

logging:
  level:
    com.example.clients.UserService: DEBUG

Ondersteunde logniveaus:

  • NONE: Geen logging (standaard)
  • BASIC: Logt alleen de verzoeksmethode, URL, antwoordstatuscode en uitvoeringstijd
  • HEADERS: Logt basisinformatie samen met verzoek- en antwoordheaders
  • FULL: Logt headers, body en metadata voor zowel verzoeken als antwoorden

Foutafhandeling

Eigen error decoder

@Component
public class CustomErrorDecoder implements ErrorDecoder {
    
    private final ErrorDecoder defaultErrorDecoder = new Default();
    
    @Override
    public Exception decode(String methodKey, Response response) {
        if (response.status() >= 400 && response.status() < 500) {
            return new ClientException("Client error: " + response.status());
        } else if (response.status() >= 500) {
            return new ServerException("Server error: " + response.status());
        }
        return defaultErrorDecoder.decode(methodKey, response);
    }
}

Registreren in de configuratie

@Configuration
public class FeignConfig {
    
    @Bean
    public ErrorDecoder errorDecoder() {
        return new CustomErrorDecoder();
    }
}

Feign-clients testen

Unit-tests

@ExtendWith(MockitoExtension.class)
class OrderProcessingServiceTest {
    
    @Mock
    private UserService userService;
    
    @Mock
    private OrderService orderService;
    
    @InjectMocks
    private OrderProcessingService orderProcessingService;
    
    @Test
    void shouldProcessOrderSuccessfully() {
        // Given
        Long userId = 1L;
        User user = new User(userId, "John Doe");
        CreateOrderRequest request = new CreateOrderRequest();
        Order expectedOrder = new Order(1L, userId);
        
        when(userService.getUser(userId)).thenReturn(user);
        when(orderService.createOrder(any(), anyString())).thenReturn(expectedOrder);
        
        // When
        Order result = orderProcessingService.processOrder(userId, request);
        
        // Then
        assertThat(result).isEqualTo(expectedOrder);
        verify(userService).getUser(userId);
        verify(orderService).createOrder(request, anyString());
    }
}

Integratietests

@SpringBootTest
@AutoConfigureTestDatabase
class FeignIntegrationTest {
    
    @Autowired
    private UserService userService;
    
    @Test
    void shouldGetUserFromRemoteService() {
        // When
        User user = userService.getUser(1L);
        
        // Then
        assertThat(user).isNotNull();
        assertThat(user.getId()).isEqualTo(1L);
    }
}

Met deze stappen kun je snel aan de slag met OpenFeign om microservicecommunicatie te vereenvoudigen. De volgende hoofdstukken introduceren meer geavanceerde functies en best practices.