#
OpenFeign
This tutorial explains how to use Spring Cloud OpenFeign. This tutorial contains an example as well.
OpenFeign is a way we can call a service without using the well-known RestTemplate class.
For implementing this, first of all we need to create a simple Spring Boot application using spring initializr as in the image below:
What is important is to have the following dependency in pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
Now we need to add @EnableFeignClients
annotation to the main class of the application.
Now the main class will look like this:
package com.example.openfeign;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class OpenFeignApplication {
public static void main(String[] args) {
SpringApplication.run(OpenFeignApplication.class, args);
}
}
We need to add the @FeignClient
to an interface. This interface defines the call to the external API.
In my case the interface looks like:
package com.example.openfeign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name="myInterfaceName", url="https://www.boredapi.com/api")
public interface MyInterface {
@GetMapping("/activity")
String getMyServiceCall1();
}
myInterfaceName
: is the name of the interface (could be any name)
https://www.boredapi.com/api
: the base URL for the external call
/activity
: will be added to the base URL for creating the final URL
Info
Instead adding url="https://www.boredapi.com/api"
in the interface annotation we can add
spring.cloud.openfeign.client.config.myInterfaceName.url=https://www.boredapi.com/api
in
application.properties configuration file. In the last approach we can configure better the
OpenFeign client.
Now we can define the application controller:
package com.example.openfeign;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
final MyInterface myInterface;
public MyController(MyInterface myInterface) {
this.myInterface = myInterface;
}
@GetMapping("/call")
public String status() {
var var1 = myInterface.getMyServiceCall1();
return var1;
}
}
That's all.
Now we start our Spring Boot application, and we put http://localhost:8080/call
address in a browser.
In Firefox, we can see the following :
What we can see is what we receive from https://www.boredapi.com/api/activity GET call.
Enjoy OpenFeign ! It is easy !