Spring Cloud (11) Infamous service invocation: Use of feign (Part one)

Source: Internet
Author: User

First, write in front

Recent development task is busy, work also began to exercise, this series of articles put a long time, see GitHub I submitted feign of the entry procedure has been a long time, today just hollow, this is more on a post, ready to divide a few parts write

Note: In the previous projects, the author ignores a problem, in the Pom file if the parent node is spring-cloud-starter-parent instead of spring-boot-starter-parent, So you don't have to write the following code.

    <dependencyManagement>        <dependencies>            <dependency>                <groupId>org.springframework.cloud</groupId>                <artifactId>spring-cloud-dependencies</artifactId>                <version>Camden.SR3</version>                <type>pom</type>                <scope>import</scope>            </dependency>        </dependencies>    </dependencyManagement>
Ii. introduction of Feign

Through the previous study of the Ribbon and hystrix to develop, through these two heavy weapons learned how to achieve client-side load balancing, service invocation and break-through protection, in practice, we found that these two basic tools are always in pairs, then there is no higher level of encapsulation to simplify development?

Spring provides us with spring Cloud feign, a tool that is based on Netflix feign, with the exception of load balancing, service invocation, and break-out protection. It also provides a way to define declarative Web service clients and support for annotations that are compatible with SPRINGMVC.

Iii. Quick Start

Continue to use the entire project before, no classmate of this project please clone down code, address: Https://github.com/HellxZ/SpringCloudLearn.git

Create a new project named FeignCustomer ,

Pom.xml as follows:

<?xmlVersion= "1.0" encoding= "UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>Com.cnblogs.hellxz</groupId>    <artifactId>Feigncustomer</artifactId>    <version>1.0-snapshot</version>    <parent>        <groupId>Org.springframework.cloud</groupId>        <artifactId>Spring-cloud-starter-parent</artifactId>        <version>Dalston.sr5</version>        <relativePath/>    </parent>    <dependencies>        <!--Hystrix,feign is based on Hystrix- -        <dependency>            <groupId>Org.springframework.cloud</groupId>            <artifactId>Spring-cloud-starter-hystrix</artifactId>        </dependency>        <!--Eureka Dependencies, the connection to the registry needs to have this dependency- -        <dependency>            <groupId>Org.springframework.cloud</groupId>            <artifactId>Spring-cloud-starter-eureka</artifactId>        </dependency>        <!--feign dependency, declarative development--        <dependency>            <groupId>Org.springframework.cloud</groupId>            <artifactId>Spring-cloud-starter-feign</artifactId>        </dependency>        <!--SPRINGMVC dependent --        <dependency>            <groupId>Org.springframework.boot</groupId>            <artifactId>Spring-boot-starter-web</artifactId>        </dependency>    </dependencies>    <build>        <plugins>            <plugin>                <groupId>Org.springframework.boot</groupId>                <artifactId>Spring-boot-maven-plugin</artifactId>            </plugin>            <plugin>                <groupId>Org.apache.maven.plugins</groupId>                <artifactId>Maven-compiler-plugin</artifactId>                <configuration>                    <source>1.8</source>                    <target>1.8</target>                </configuration>            </plugin>        </plugins>    </build></project>

As usual resources under the package createapplication.yml

server:  port: 9001spring:  application:    name: feign-customereureka:  client:    serviceUrl:      defaultZone: http://peer1:1111/eureka

Create a main class that is more support than just adding @EnableFeignClients to turn on feign

package com.cnblogs.hellxz;import org.springframework.boot.SpringApplication;import org.springframework.cloud.client.SpringCloudApplication;import org.springframework.cloud.netflix.feign.EnableFeignClients;@EnableFeignClients//开启Feign@SpringCloudApplicationpublicclass FeignApp {    publicstaticvoidmain(String[] args) {        SpringApplication.run(FeignApp.class, args);    }}

In addition to the above we need a tool to invoke the service provider, in the Ribbon chapter we are using Resttemplate,feign is a declarative invocation tool, let's explore

In the com.cnblogs.hellxz.client creation EurekaServiceFeign , this is used as service-like usage, the code is as follows:

Package com.cnblogs.hellxz.client;import org.springframework.cloud.netflix.feign.FeignClient;import org.springframework.web.bind.annotation.RequestMapping;import Org.springframework.web.bind.annotation.RequestMethod;/*** Service provider's feign* This interface is equivalent to treating the original service provider project as a services class,* We just need to declare it in the name of the Feign-client and will automatically go to call the registry for the name of the service* A simpler understanding is that value is equivalent to the parent path of the controller class in MVC, invoking the service through the parent path + subpath and Parameters */@FeignClient(Value ="Eureka-service")//Where value is the name of the service to invoke Public Interfaceeurekaservicefeign {/*** First feign code* There is no native @getmapping/@PostMapping/@DeleteMapping/@PutMapping in feign, to specify the method to be used     */    @RequestMapping(Value ="/hello", Method=requestmethod.GET) Stringhellofeign();}

I just said we could use this feign as a service to get the return value using the services provider's method, here we write a controller to demonstrate the use of

Package Com.cnblogs.hellxz.controller;import com.cnblogs.hellxz.client.EurekaServiceFeign;import org.springframework.beans.factory.annotation.Autowired;import Org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controller@RequestMapping("Feign") Public classHellocontroller {@Autowired    PrivateEurekaservicefeign eurekaservicefeign;//Injection feign    @GetMapping("/hello")@ResponseBody     PublicStringSayHello(){//method that calls feign in a method        returnEurekaservicefeign.hellofeign(); }}

Well, we started the registry, the service provider, and this feign project separately.

Use postman for testing, access with GET requesthttp://localhost:9001/feign/hello

Four, parameter binding

Spring official in the integration of Netflix feign, added SPRINGMVC annotation support, which makes feign accustomed to SPRINGMVC programmers better transition over, let me give a few examples, the most commonly used in the project.

1. @PathVariable

Extension EurekaServiceFeign , add the following code, comments very detailed, not much to say

    /**     * 在服务提供者我们有一个方法是用直接写在链接,SpringMVC中用的@PathVariable     * 这里边和SpringMVC中有些有一点点出入,SpringMVC中只有一个参数而且参数名的话是不用额外指定参数名的,而feign中必须指定     */    @RequestMapping"/greet/{dd}",method = RequestMethod.GET)    greetFeign(@PathVariable("dd") String dd);

HelloControlleralso add the corresponding code in, to call the method above

    /**     * 注意这里是SpringMVC,URL中的参数与方法中的参数名相同无需在注解中注明参数名     */    @GetMapping("/greet/{test}")    @ResponseBody    publicgreet(@PathVariable String test){        return eurekaServiceFeign.greetFeign(test);    }

Test this method

2. @RequestParam

Add a method to a class that is known as feign, and invoke the method of the service provider

The user class used in the following code is copied from the service provider module

    /**     * 这里说下@RequestParam 注解和SpringMVC中差别也是不大,我认为区别在于Feign中的是参数进入URL或请求体中,     * 而SpringMVC中是参数从请求体中到方法中     * @param ids id串,比如“1,2,3”     * @return     */    @RequestMapping"/users",method = RequestMethod.GET)    publicgetUsersByIds(@RequestParam("ids") List<Long> ids);

method to call this method

    /**     * 调用Feign中使用@RequestParam的方法     */    @GetMapping("/users")    @ResponseBody    publicgetUserListByIds(@RequestParam("ids") List<Long> ids){      return eurekaServiceFeign.getUsersByIds(ids);    }

Test

3. @RequestHeader

Here is an annotation for adding parameters to the header of the request, but before our service provider does not have this method, here is GetRequestController a method to add the following

    @GetMapping("/headers")    publicgetParamByRequestHeader(@RequestHeader("name") String name){        return name;    }

Now let's add a method that calls the top method for the feign class

    /**     * 这里是将参数添加到Headers中     * @param name 参数     */    @RequestMapping"/headers")    getParamByHeaders(@RequestHeader("name") String name);

In the controller, add the code

    @GetMapping("/headers")    @ResponseBody    publicgetParamByHeaders(@RequestHeader("name") String name){        return eurekaServiceFeign.getParamByHeaders(name);    }

Test

5. @RequestBody

Using this annotation requires a POST request, here is a simple example

Adding methods to the Feign class

    /**     * 调用服务提供者的post方法,接收回来再被服务提供者丢回来     * @param user User对象     */    @RequestMapping"/user", method = RequestMethod.POST)    getUserByRequestBody(@RequestBody User user);

Controller in the Add

    @PostMapping("/requestBody")    @ResponseBody    publicgetParamByRequestBody(@RequestBody User user){        return eurekaServiceFeign.getUserByRequestBody(user);    }

Test

Note that @RequestParam and @RequestHeader , as well as the first mentioned @PathVariable three annotations are required to specify the parameter name, which is different from SPRINGMVC, otherwise will be reported illegalstateexception exception, so be sure to indicate the parameter name!

The time is not early, and tomorrow continues more

Spring Cloud (11) Infamous service invocation: Use of feign (Part one)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.