1. 程式人生 > >SpringCloud學習之feign

SpringCloud學習之feign

ice pin tro 分享 int 關於 security eve ket

一.關於feigin

  feigin是一種模板化,聲明式的http客戶端,feign可以通過註解綁定到接口上來簡化Http請求訪問。當然我們也可以在創建Feign對象時定制自定義解碼器(xml或者json等格式解析)和錯誤處理。

二.添加SpringCloud對feign的支持

gradle配置:

技術分享圖片
compile(‘org.springframework.cloud:spring-cloud-starter-feign‘)
View Code

feigin最基本使用方法:

技術分享圖片
 1 interface GitHub {
 2   @RequestLine("GET /repos/{owner}/{repo}/contributors")
3 List<Contributor> contributors(@Param("owner") String owner, @Param("repo") String repo); 4 } 5 6 static class Contributor { 7 String login; 8 int contributions; 9 } 10 11 public static void main(String... args) { 12 GitHub github = Feign.builder() 13 .decoder(new
GsonDecoder()) 14 .target(GitHub.class, "https://api.github.com"); 15 16 // Fetch and print a list of the contributors to this library. 17 List<Contributor> contributors = github.contributors("OpenFeign", "feign"); 18 for (Contributor contributor : contributors) {
19 System.out.println(contributor.login + " (" + contributor.contributions + ")"); 20 } 21 }
View Code

feign發送json與xml的格式的http請求:

技術分享圖片
 1 interface LoginClient {
 2 
 3   @RequestLine("POST /")
 4   @Headers("Content-Type: application/xml")
 5   @Body("<login \"user_name\"=\"{user_name}\" \"password\"=\"{password}\"/>")
 6   void xml(@Param("user_name") String user, @Param("password") String password);
 7 
 8   @RequestLine("POST /")
 9   @Headers("Content-Type: application/json")
10   // json curly braces must be escaped!
11   @Body("%7B\"user_name\": \"{user_name}\", \"password\": \"{password}\"%7D")
12   void json(@Param("user_name") String user, @Param("password") String password);
13 }
View Code

註意示例中需要添加對gson的支持

feign發送https信任所有證書的代碼:

技術分享圖片
 1 final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
 2             @Override
 3             public void checkClientTrusted(
 4                     java.security.cert.X509Certificate[] chain,
 5                     String authType) {
 6             }
 7 
 8             @Override
 9             public void checkServerTrusted(
10                     java.security.cert.X509Certificate[] chain,
11                     String authType) {
12             }
13 
14             @Override
15             public java.security.cert.X509Certificate[] getAcceptedIssuers() {
16                 return null;
17             }
18         }};
19         final SSLContext sslContext = SSLContext.getInstance("TLSv1");
20         sslContext.init(null, trustAllCerts,
21                 new java.security.SecureRandom());
22         // Create an ssl socket factory with our all-trusting manager
23         final SSLSocketFactory sslSocketFactory = sslContext
24                 .getSocketFactory();
25         Feign.builder().client(new Client.Default(sslSocketFactory, (s, sslSession) -> true));
View Code

三.在SpringCloud中使用Feign

比如說註冊中心有如下服務:

技術分享圖片

1)application.yml的配置:

技術分享圖片
spring:
  application:
    name: demo-consumer
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8080/eureka,http://localhost:8081/eureka
server:
  port: 8090
View Code

2)創建接口

技術分享圖片
 1 package com.bdqn.lyrk.consumer.demo.api;
 2 
 3 import org.springframework.cloud.netflix.feign.FeignClient;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 
 6 @FeignClient("demo")
 7 public interface DemoConfigService {
 8 
 9     @RequestMapping("/demo.do")
10     String demoService();
11 }
View Code

註意在接口上加上註解:@FeignClient("demo") 註解裏的參數是在eureka註冊的服務名

3)編寫啟動類:

技術分享圖片
package com.bdqn.lyrk.consumer.demo;

import com.bdqn.lyrk.consumer.demo.api.DemoConfigService;
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.context.ConfigurableApplicationContext;

@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class DemoConsumerProvider {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(DemoConsumerProvider.class, args);
        DemoConfigService demoConfigService = applicationContext.getBean(DemoConfigService.class);
        System.out.println(demoConfigService.demoService());
    }
}
View Code

註意在啟動類上加上@EnableFeignClients來開啟Feign功能

運行後輸出:

技術分享圖片

此時我們可以發現使用feign客戶端我們訪問服務的代碼簡介了好多

SpringCloud學習之feign