REST Clients With OpenFeign: How to Implement Them
In this article, readers will learn how to implement REST clients with the Spring Cloud OpenFeign module and how to configure them.
Join the DZone community and get the full member experience.
Join For FreeIn previous posts, we have seen how to implement distributed configuration and service discovery in Spring Cloud. In this article, we will discuss how to implement REST calls between microservices. We will implement REST clients with OpenFeign software.
Services Communication
There are two main styles of service communication: synchronous and asynchronous. The asynchronous type involves calls where the thread making the call does not wait for a response from the server and is not blocked. A typical protocol used for such scenarios is AMQP. This protocol involves messaging architectures, with message brokers like RabbitMQ and Apache Kafka.
Asynchronous calls are also possible with REST protocol. The Spring Boot WebClient technology, available in the Spring Web Reactive module, provides that. Nevertheless, in this article, we are not discussing this communication style. We will talk about synchronous REST calls instead. The technology we are going to describe for doing synchronous REST calls is the OpenFeign package.
OpenFeign
Feign is a former Netflix component, then moved to the open-source community as OpenFeign. With OpenFeign, we can implement REST clients in a declarative way. This has some analogy with Spring Data repositories. We will define the interfaces with REST method definitions, and the framework will generate the client part under the hood.
The stack we are using in this article is:
- Spring Boot: 3.2.1
- Spring Cloud: 2023.0.0 release train.
- Java 17
REST Clients With OpenFeign: Basic Configuration
To enable OpenFeign for a Spring Boot project, we have to add the following dependency in the pom.xml file:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
The next step would be to annotate the Spring configuration class with the @EnableFeignClients annotation:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class AppMain {
public static void main(String[] args) {
SpringApplication.run(AppMain.class, args);
}
}
We can add several parameters to this annotation. For instance, we can specify base packages and explicitly list the client implementations:
@EnableFeignClients(basePackages = {"com.codingstrain.springcloud.sample.libraryapp.books.client"}, clients = { AuthorClient.class, ReviewClient.class })
This allows us to avoid unnecessary scanning of packages and classes. As seen in the next section, we can also define a configuration class by the defaultConfiguration parameter.
REST Clients With OpenFeign: Customization
OpenFeign is made of a set of sub-components defined by specific interfaces. It is distributed with a default set of implementations of those interfaces. We can customize this set and override the implementations by specifying a configuration class in the @EnableFeignClients annotation:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(defaultConfiguration = BookClientConfiguration.class)
public class AppMain {
public static void main(String[] args) {
SpringApplication.run(AppMain.class, args);
}
}
Some of the default implementations of the OpenFeign components are:
- Decoder: The default implementation is ResponseEntityEncoder.
- Encoder: The default implementation is SpringEncoder.
- Logger: The default implementation is Slf4jLogger.
- Contract: The default implementation is SpringMvcContract. It serves the purpose of providing annotation processing.
- Client: According to the documentation if the Spring Cloud Load Balancer library is on the classpath the FeignBlockingLoadBalancerClient is used. Spring Cloud Load Balancer is included in the spring-cloud-dependencies release train 2023.0.0 described in this article.
We can override one or more components by redefining the related beans in the configuration class:
@Configuration
public class BookClientConfiguration {
@Bean
public Contract feignContract() {
return new SpringMvcContract();
}
...
}
We can also configure OpenFeign programmatically by using a Feign builder:
Feign.builder()
.client(new ApacheHttpClient())
.build();
A further possibility is to customize the configuration by properties files. For instance, we can specify a specific service name like in the following example:
feing:
client:
config:
author-service:
connectTimeout: 5000
If we set "default" instead of "author-service", the above setting will be valid for all services.
REST Clients With OpenFeign: Client Interfaces
Client Definitions
To define the REST clients for the application, we have to write their interfaces with the appropriate mappings. It is up to the framework to provide their implementations at runtime. To inform the framework that those interfaces are meant to be OpenFeign clients, we must use the @FeignClient annotation:
@FeignClient(name = "author-service")
public interface AuthorClient {
@GetMapping("/author/{name}")
public Optional<Author> findByName(@PathVariable("name") String name);
}
@FeignClient(name = "review-service")
public interface ReviewClient {
@GetMapping("/review/{bookTitle}")
public List<Review> findByBookTitle(@PathVariable("bookTitle") String bookTitle);
}
OpenFeign can automatically interact with a discovery server. If we configure our application to use Eureka, for example, the name parameter above would represent the actual name of a service in the discovery registry. An alternative would be to specify an explicit URL by the url parameter.
Making Use of Inheritance
There is a way to write cleaner code for the OpenFeign clients by using inheritance. We can define all the methods and mappings in an interface:
public interface AuthorRESTService {
@GetMapping("/author/{name}")
public Optional<Author> findByName(@PathVariable("name") String name);
}
Then we can implement that interface in a controller. This way we can inherit the mapping annotations from the above interface:
@RestController
@RequestMapping("/library")
public class AuthorController implements AuthorRESTService {
@Autowired
private AuthorService authorService;
@Override
public Optional<Author> findByName(@PathVariable("name") String name) {
return authorService.findByName(name);
}
}
As for the client, we can extend the interface and there's no need to define any method at all. We just need to annotate the method with @FeignClient, and provide the service name:
@FeignClient(name = "author-service")
public interface AuthorClient extends AuthorRESTService {
}
REST Clients With OpenFeign: Using the Clients
We can use the REST client implementations by simply injecting the above-defined interfaces. For instance, we can inject them into a Spring service component:
@Service("bookService")
public class BookService {
Logger logger = LoggerFactory.getLogger(BookService.class);
@Autowired
private AuthorClient authorClient;
@Autowired
private ReviewClient reviewClient;
@Autowired
private BookRepository bookRepository;
public BookInfo findBookInfoByTitle(@RequestParam("authorName") String authorName, @RequestParam("bookTitle") String bookTitle) {
Optional<Author> author = authorClient.findByName(authorName);
List<Review> reviews = reviewClient.findByBookTitle(bookTitle);
BookInfo bookInfo = new BookInfo();
bookInfo.setAuthorBiography(author.get()
.getBiography());
bookInfo.setAuthorName(authorName);
List<String> reviewContents = reviews.stream()
.map(item -> item.getContent())
.collect(Collectors.toList());
bookInfo.setTitle(bookTitle);
bookInfo.setBookReviews(reviewContents);
return bookInfo;
}
...
}
In the above example, the authorClient and reviewClient OpenFeign clients are used to extract some information related to a book item. Then, the information is returned by a BookInfo object. Having defined the Spring service this way, we can then use it inside a controller:
@RestController
@RequestMapping("/library")
public class BookController {
Logger logger = LoggerFactory.getLogger(BookService.class);
@Autowired
private BookService bookService;
@GetMapping(value = "/bookInfo", params = { "authorName", "bookTitle" })
public BookInfo findBookInfoByTitle(@RequestParam("authorName") String authorName, @RequestParam("bookTitle") String bookTitle) {
return bookService.findBookInfoByTitle(authorName, bookTitle);
}
...
}
Running an Example
The code from this article is available on GitHub. The logic behind the example is very simple. We have a microservice named book-service representing the backend of an application that allows browsing books. From a specific book, the book-service microservice can get the author's biography and book reviews by the author's name and book title. This information is fetched by calling two other services, author-service and review-service.
The set of modules includes a Eureka discovery service:
- libraryapp-discovery-server: A Eureka discovery server
- libraryapp-discovery-authors: Allows to get book author biography
- libraryapp-discovery-reviews: Allows to get book reviews
- libraryapp-discovery-books: Uses the author and review service to get the author's biography and reviews of a specific book
The single modules register themselves on the discovery registry by the following piece of configuration in the yaml configuration file:
eureka:
client:
serviceUrl:
defaultZone: http://myusername:mypassword@localhost:8760/eureka/
We can compile the modules and launch all the instances by the following commands:
- discovery-service: "java - jar libraryapp-discovery-server-1.0-SNAPSHOT.jar"
- author-service: "java - jar libraryapp-discovery-authors-1.0-SNAPSHOT.jar"
- review-service: "java - jar libraryapp-discovery-reviews-1.0-SNAPSHOT.jar"
- book-service: "java - jar libraryapp-discovery-books-1.0-SNAPSHOT.jar"
Just to see how traffic is distributed, we can launch two instances of author-service, overriding the port setting:
- java - jar libraryapp-discovery-authors-1.0-SNAPSHOT.jar --PORT=8084
- java - jar libraryapp-discovery-authors-1.0-SNAPSHOT.jar --PORT=8085
We expect the traffic toward author-service to be equally balanced between the two instances, in a round-robin fashion, which is the default.
Conclusion
A core feature of microservice architectures is the remote communication between services. In this article, we have discussed the synchronous REST scenario. Spring Cloud is gradually shifting its all stack, abandoning the Netflix OSS components. Feign is still there, as its open community OpenFeign counterpart, and still offers a valid and highly configurable solution.
Published at DZone with permission of Mario Casari. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments