springcloud(第八篇)springcloud feign

來源:互聯網
上載者:User

# spring cloud feign introduction

netflix feign是一個類似retrofit進行http調用架構,Feign makes writing java http clients easier 使得編寫http client代碼更加簡單 netflix feign

直接給出一段簡單的案例

package com.lkl.netflix.feign;import feign.*;import feign.codec.ErrorDecoder;import feign.codec.Decoder;import feign.gson.GsonDecoder;import java.io.IOException;import java.util.List;/** * Created by liaokailin on 16/5/9. */public class GitHubExample {    interface GitHub {  // 1        @RequestLine("GET /repos/{owner}/{repo}/contributors")        List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo);    }    public static void main(String... args) {        Decoder decoder = new GsonDecoder();  // 2        GitHub github = Feign.builder()                .decoder(decoder) // 3                .errorDecoder(new GitHubErrorDecoder(decoder))  // 4                .logger(new Logger.ErrorLogger())  // 5                .logLevel(Logger.Level.BASIC)  // 5                .target(GitHub.class, "https://api.github.com");  // 6        System.out.println("Let's fetch and print a list of the contributors to this library.");        List<Contributor> contributors = github.contributors("netflix", "feign");  // 7        for (Contributor contributor : contributors) {            System.out.println(contributor.login + " (" + contributor.contributions + ")");        }        System.out.println("Now, let's cause an error.");        try {            github.contributors("netflix", "some-unknown-project");  // 8        } catch (GitHubClientError e) {            System.out.println(e.getMessage());        }    }    static class Contributor {        String login;        int contributions;    }    static class GitHubClientError extends RuntimeException {  // 4        private String message; // parsed from json        @Override        public String getMessage() {            return message;        }    }    static class GitHubErrorDecoder implements ErrorDecoder {   // 4        final Decoder decoder;        final ErrorDecoder defaultDecoder = new ErrorDecoder.Default();        GitHubErrorDecoder(Decoder decoder) {            this.decoder = decoder;        }        @Override        public Exception decode(String methodKey, Response response) {            try {                return (Exception) decoder.decode(response, GitHubClientError.class);            } catch (IOException fallbackToDefault) {                return defaultDecoder.decode(methodKey, response);            }        }    }}

1.首先定義介面GitHub,使用註解RequestLine 表明contributors()方法為一個get請求,請求相對為/repos/{owner}/{repo}/contributors
2.Decoder decoder = new GsonDecoder(); 建立一個GsonDecoder解碼器,表明通過Gson解析返回資料
3.decoder()方法設定解碼器
4.errorDecoder()指定發生異常時的解碼器,需要實現ErrorDecoder介面,覆寫decode方法,通過指定的Decoder解析錯誤資訊,這裡還是使用GsonDecoder
5.logger 相關的表示配置日誌系你系
6.target() 方法指定訪問url以及返回的類型
7.通過建立的github對象調用contributors擷取結果
8.類比異常情況

note: feign使用起來很簡單,其原理和retrofit及其類似,通過介面定義訪問訪問,用jdk的動態代理建立介面的實作類別,在類中解析方法上的註解資訊用以識別使用者配置的http請求資訊,然後執行請求;
feign可以通過ReflectiveFeign下的newInstance()方法看到

return (T) Proxy        .newProxyInstance(target.type().getClassLoader(), new Class<?>[]{target.type()}, handler);
spring cloud feign

spring cloud feign通過註解的封裝使用起來更加簡單

package com.lkl.springcloud.feign;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.cloud.netflix.feign.EnableFeignClients;import org.springframework.cloud.netflix.feign.FeignClient;import org.springframework.context.annotation.Configuration;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import java.util.List;/** * Created by liaokailin on 16/5/11. */@Configuration@EnableAutoConfiguration@EnableFeignClients@RestControllerpublic class Application {    @Autowired    GitHub gitHub;    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }    @FeignClient(url = "https://api.github.com")    interface GitHub {        @RequestMapping(value = "/repos/{owner}/{repo}/contributors", method = RequestMethod.GET)      ResponseEntity<List<Contributor>> contributors(@PathVariable("owner") String owner, @PathVariable("repo") String repo);    }    @RequestMapping("/")    public void test(){        ResponseEntity< List<Contributor>>  responseEntity  =   gitHub.contributors("netflix", "feign");        List<Contributor> contributors = responseEntity.getBody();         for (Contributor contributor : contributors) {         System.out.println(contributor.login + " (" + contributor.contributions + ")");         }    }    static class Contributor {        String login;        int contributions;    }}

註解EnableFeignClients表明需要掃描使用FeignClient註解的介面,在代碼中定義了@FeignClient(url = "https://api.github.com") 表明該介面為一個feign介面
通過url指定訪問路徑RequestMapping表明相對路徑

在代碼中注入beanGitHub,直接調用其中申明的方法即可。

重點說明下FeignClient註解

該註解表示申明建立一個rest client bean,可以直接通過Autowired注入使用,如果ribbon在工程中啟用,則會使用load balance進行後端請求調用,可以為FeignClient指定value表明需要訪問的serviceId feign + ribbon + eureka

在springcloud(第七篇)springcloud ribbon with eureka中講解了ribbon+eureka,其中使用RestTemplate進行調用,也可以通過
feign調用

package com.lkl.springcloud.feign;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.netflix.feign.EnableFeignClients;import org.springframework.cloud.netflix.feign.FeignClient;import org.springframework.cloud.netflix.ribbon.RibbonClient;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import static org.springframework.web.bind.annotation.RequestMethod.GET;/** * Created by liaokailin on 16/5/9. */@SpringBootApplication@EnableDiscoveryClient@RestController@RibbonClient("hello")@EnableFeignClientspublic class Application {    @Autowired    HelloClient client;    @RequestMapping("/")    public String hello() {        return client.hello();    }    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }    @FeignClient("simple")    interface HelloClient {        @RequestMapping(value = "/", method = GET)        String hello();    }}

使用@FeignClient("simple")指定要訪問的service id 由於hello()對應的mapping為@RequestMapping(value = "/", method = GET) 那麼該方法實際調用url為
http://simple/,因此在執行

@RequestMapping("/")    public String hello() {        return client.hello();    }

調用的為SimpleApplication.java中

@RequestMapping("/")    public String hello() {        return "Hello";    }

ok ~ it’s work ! more about is here
轉載請註明
http://blog.csdn.net/liaokailin/article/details/51470051

歡迎關注,您的肯定是對我最大的支援

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.