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.

Example

Introducing dependency packages

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.0.RELEASE</version>
</dependency>

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 {
    @RequestMapping("/employee/hello")
    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

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ProviderclientApplication {
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Bean
    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

@RestController
@RequestMapping("getEmployeeController")
public class GetEmployeeController {

    @Autowired
    private RestTemplate restTemplate;
    //injection
    @Autowired
    private FeginService feginService;

    //@Autowired
    //private LoadBalancerClient loadBalancerClient;

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

    @RequestMapping("testFeign")
    public String testFeign() {
        return feginService.hello();
    }

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

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