A Simple Fegin Example of Sprcloud

Keywords: Spring

Feign definition:

Feign is a declarative Web service client. It makes it easier to write Web service clients. To use Feign, create an interface and annotate it. It has pluggable annotation support, including Feign annotations and JAX-RS annotations. Feign also supports pluggable encoders and decoders. Spring Cloud adds support for Spring MVC annotations and uses the same HttpMessageConverters that are used by default in Spring Web. Spring Cloud integrates Ribbon and Eureka to provide load balancing http clients when using Feign.


Introducing dependency packages


New Fegin Interface

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value = "employee-msg-provider")
public interface FeginService {
    String hello();

    @RequestMapping(value = "/employee/findById", method= RequestMethod.GET)
    String findById(@RequestParam("id") int name) ;

Resolution: employee-msg-provider is the name of the service to be invoked, and the interface is defined on the caller.

Start class to add EnableFeignClients annotations

public class ProviderclientApplication {
    public RestTemplate restTemplate() {
        return new RestTemplate();

    public IRule myRule() {
        //Specify retry strategy, random strategy
        return new RandomRule();

    public static void main(String[] args) {
        SpringApplication.run(ProviderclientApplication.class, args);


Here's how to call other service interfaces with restTemplate

public class GetEmployeeController {

    private RestTemplate restTemplate;
    private FeginService feginService;

    //private LoadBalancerClient loadBalancerClient;

    //Initially, other services were invoked with restTemplate
    public Employee findById(@PathVariable int id) {
        Employee employee = this.restTemplate.getForObject("http://employee-msg-provider/employee/findById?id=" + id, Employee.class);
        return employee;

    public String testFeign() {
        return feginService.hello();

    //Use feign for other services
    public String feignFindById(int id) {
        return feginService.findById(id);

Posted by tkj on Tue, 08 Oct 2019 12:31:49 -0700