Springcloud (9): Using feign to implement declarative rest calls

Source: Internet
Author: User

First, Introduction

Before we implemented the REST API call using Resttemplate, the code is as follows:

@GetMapping ("/user/{id}") Public user FindByID (@PathVariable Long id) throws Exception {return this.restTemplate.getFo Robject ("http://spring-ribbon-eureka-client2/" + ID, user.class);}

From the above code, we are using the concatenation URI, if too many parameters, it will be very troublesome, the way to solve is to use feign.


Feign is a declarative, templated HTTP client developed by Netflix, and feign can help us make it easier and more elegant to invoke HTTP APIs.

Spring Cloud has enhanced feign, feign supports SPRINGMVC annotations, and integrates the Ribbon and Eureka.

Second, for the service consumer integration feign

2.1. Add dependencies

<dependency> <groupId>org.springframework.cloud</groupId> <artifactId> Spring-cloud-starter-feign</artifactid></dependency>

2.2. Create a feign interface and add @feignclient annotations

Package Com.example.demo.feign;import Com.example.demo.pojo.user;import Org.springframework.cloud.netflix.feign.feignclient;import org.springframework.web.bind.annotation.PathVariable ; Import Org.springframework.web.bind.annotation.requestmapping;import org.springframework.web.bind.annotation.requestmethod;/** * Description * * @Author: I love Big gold * @Description: Description * @Date: Create in 10 : 2017/7/17 */@FeignClient (name = "Spring-ribbon-eureka-client2") public interface Userfeignclient {@RequestMapping ( Value = "/{id}", method = requestmethod.get) public User FindByID (@PathVariable ("id") Long ID) throws Exception;}

Description

1. The spring-ribbon-eureka-client2 in the @FeignClient annotation is an arbitrary client name used to create the ribbon load balancer.

2. Because this instance uses EUREKA, the Ribbon parses spring-ribbon-eureka-client2 into a service in the Eureka Server service registry.

3. If you do not want to use Eureka, you can use the Service.ribbon.listOfServers property to configure the server list.


2.3. Add feign to Controller

@RestControllerpublic class Usercontroller {@Autowired private userfeignclient userfeignclient;            @GetMapping ("/user/{id}") Public user FindByID (@PathVariable Long id) throws Exception {if (null = = ID) {        return null;    } return This.userFeignClient.findById (ID); }}


2.4. Modify the Startup class to add @enablefeignclients annotations to it

Package Com.example.demo;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.springbootapplication;import Org.springframework.cloud.netflix.eureka.enableeurekaclient;import org.springframework.cloud.netflix.feign.enablefeignclients;@ Enableeurekaclient@enablefeignclients@springbootapplicationpublic class Springfeignconsumerapplication {public   static void Main (string[] args) {Springapplication.run (springfeignconsumerapplication.class, args); }}

Third, custom feign configuration

In spring cloud, the default configuration class for feign is Feignclientsconfiguration, which defines the encoders, decoders, contracts used, etc. that are used by the feign by default.

Spring Cloud allows you to customize the configuration of the feign by annotating the Configura property of the @feignclient, which has a higher priority than feignclientsconfiguration for custom configurations .

In addition, although some configurations do not provide a default value, SPIRNG also scans the types listed (that is, the configuration can be customized)


Example: Customize the configuration of the feign to work with annotations that are feign.

Note: The code is based on the above engineering

3.1. Create a feign configuration class

Package com.example.demo.config;import com.example.demo.excludefromcomponentscan;import feign. contract;import org.springframework.context.annotation.bean;import  Configuration classes for Org.springframework.context.annotation.configuration;/** * feign  *  Note: This class should not be in the @componetscan of the main application context  *  @Author:  I love Big gold  *  @Description:  feign's configuration class   *  @Date:  create in 15:57 2017/7/17 */@ configuration@excludefromcomponentscanpublic class feignconfiguration {     /**     *  the contract to feign the native default contract. This allows you to use feign's own annotations      *  @Author:  I love big gold      *   @Description:  To change the contract to the feign native default contract. This allows you to use feign's own annotations      *  @Date: 16:02 2017/7/17      *  @return   Default feign contract      */     @Bean     &nbSp;public contract feigncontract ()  {        return  new contract.default ();     }}
Package Com.example.demo;public @interface Excludefromcomponentscan {}

3.2. Modification Feign Interface

package com.example.demo.feign;import com.example.demo.config.feignconfiguration;import  Com.example.demo.pojo.user;import feign. Param;import feign. requestline;import org.springframework.cloud.netflix.feign.feignclient;import  org.springframework.web.bind.annotation.pathvariable;import  org.springframework.web.bind.annotation.requestmapping;import  org.springframework.web.bind.annotation.requestmethod;/** *  Description  * *  @Author:  I love big gold  *  @Description:  description  *  @Date: create in 10:14 2017/7/17  */@FeignClient (name =  "Spring-ribbon-eureka-client2", configuration =  Feignconfiguration.class) public interface userfeignclient {    /**      *  using Feign's own annotations @requestline     *  @Author:  I love big gold      *  @Description:  use feign's own annotations @requestline     *  @Date:  17:42 2017/7/17     * @ param id  user id     *  @return   user Information      *   @throws  Exception     */     @RequestLine ("get /{ ID} ")     public user findbyid (@Param (" id ")  long id)  throws  Exception;}


Okay, OK.

3.3. Testing

Visit: HTTP://LOCALHOST:8086/USER/1

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M01/9C/23/wKiom1lsiPLTrwRfAAAUjMLU9oQ031.png "title=" 1b71cd0f-65b6-46fc-b082-1f9909b58fda.png "alt=" Wkiom1lsipltrwrfaaaujmlu9oq031.png "/>


Similarly, you can customize feign encoders, decoders, log printing, and even add interceptors for feign.

For example, some interfaces require HTTP basic-based authentication before they can be called, and the configuration class may write:

@Configuration @excludefromcomponentscanpublic class Feignconfiguration {@Bean public basicauthruestinterceptor Basi    Cauthruestinterceptor () {return new Basicauthruestinterceptor ("User", "password"); }}

Not finished, to be continued ...

This article is from "I Love Big gold" blog, please be sure to keep this source http://1754966750.blog.51cto.com/7455444/1948303

Springcloud (9): Using feign to implement declarative rest calls

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.