DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Using Spring Cloud Gateway and Discovery Service for Seamless Request Routing
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • How to Develop Microservices With Spring Cloud and Netflix Discovery
  • Full-Duplex Scalable Client-Server Communication with WebSockets and Spring Boot (Part I)

Trending

  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization
  • Orchestrating Microservices with Dapr: A Unified Approach
  1. DZone
  2. Coding
  3. Java
  4. REST Clients With OpenFeign: How to Implement Them

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.

By 
Mario Casari user avatar
Mario Casari
·
Dec. 23, 23 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
11.2K Views

Join the DZone community and get the full member experience.

Join For Free

In 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:

Java
 
@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:

Java
 
@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:

Java
 
@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:

Java
 
@Configuration
public class BookClientConfiguration {

    @Bean
    public Contract feignContract() {
          return new SpringMvcContract();
    }
...
}

We can also configure OpenFeign programmatically by using a Feign builder:

Java
 
 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:

YAML
 
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:

Java
 
@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:

Java
 
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:

Java
 
@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:

Java
 
@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:

Java
 
@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:

Java
 
@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:

YAML
 
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.

REST Spring Cloud Java (programming language) Spring Boot microservice

Published at DZone with permission of Mario Casari. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Using Spring Cloud Gateway and Discovery Service for Seamless Request Routing
  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • How to Develop Microservices With Spring Cloud and Netflix Discovery
  • Full-Duplex Scalable Client-Server Communication with WebSockets and Spring Boot (Part I)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!