Configure circuit break fallback for OpenFeign

Backend Sep 14, 2023

Lately I’ve been experimenting with microservices by following a tutorial. I have managed to set up Spring Cloud with Eureka and Feign successfully. However, I've encountered some difficulties.

In the tutorial, it provides an example using Eureka, Feign and Hystrix. However, it is using an older version of Spring Boot, while I'm using the latested version. After checking on the project page of Hystrix, I found out it was in maintanence mode. Moreover, it seems that Spring Cloud OpenFeign has also dropped support of Hystrix.

Therefore I decided to switch to another circuit breaker since this was a easier way.

Firstly, circuit breaker should be enabled

spring:
  cloud:
    openfeign:
      circuitbreaker:
        enabled: true

Then make sure to add these annotations to the application class

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication

The client class and fallback should be like this:

@FeignClient(name = "microservice-provider-user", fallback = UserFeignClientFallback.class)
public interface UserFeignClient {

    @RequestMapping("/{id}")
    User findById(@PathVariable("id") Long id);

}
@Component
class UserFeignClientFallback implements UserFeignClient {

    @Override
    public User findById(Long id) {
        User user = new User();
        user.setId(-1L);
        user.setName("user");
        return user;
    }
}

Error may poped up when using the IDE, but the code will compile, for further discussion, please see this issue. Alternative might be nested the fallback class into the interface.

@Autowired
MovieController(UserFeignClient userFeignClient) {
    this.userFeignClient = userFeignClient;
}

Tags