首頁 > Java > java教程 > 主體

spring cloud2.0學習筆記之Feign實戰

无忌哥哥
發布: 2018-07-20 12:02:45
原創
3249 人瀏覽過

背景

  • springCloud:Finchley.RELEASE

簡介

Feign是SpringCloud體系中聲明式Rest客戶端,透過簡單配置、建立介面和註解即可實現Restful服務的呼叫。而且開始支持SpringMvc了。

簡單應用程式

  • 依賴:org.springframework.cloud:spring-cloud-starter-openfeign

  • 入口加@ EnableFeignClients註解

  • 建立對應介面、加註解 

//入口类
@SpringBootApplication
@EnableFeignClientspublic class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
//原型接口声明
@FeignClient("stores")public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List getStores();    
    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);
}
登入後複製

開啟Feign斷路器與上下文支援

#feign.hystrix.enabled=true

# To disable Hystrix in Feignfeign:
  hystrix:
    enabled: true# To set thread isolation to SEMAPHORE# 将断路器隔离级别由默认的线程隔离调整为信号灯hystrix:
  command:    default:
      execution:
        isolation:
          strategy: SEMAPHORE
登入後複製

斷路器回呼
  • 斷路器支援回退,就是當斷路器開啟或介面出現錯誤時執行回呼定義的方法,傳回預先定義好的結果。開啟回呼支援只需在@FeignClient註解中配置fallback參數為介面的回呼實現類,並且回呼實現類別要被註解為Spring Bean(可以透過@Component,@Service等註解實現,詳情請參閱Spring4的註解文件)。

    @FeignClient(name = "hello", fallback = HystrixClientFallback.class)
    protected interface HystrixClient {
        @RequestMapping(method = RequestMethod.GET, value = "/hello")
        Hello iFailSometimes();
    }
    
    @Componentstatic class HystrixClientFallback implements HystrixClient {
        @Override    
        public Hello iFailSometimes() {        
            return new Hello("fallback");
        }
    }
    登入後複製

    如果需要知道回退原因可以透過回退工廠來實現,程式碼實例如下:
  • @FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
    protected interface HystrixClient {
        @RequestMapping(method = RequestMethod.GET, value = "/hello")
        Hello iFailSometimes();
    }
    
    @Componentstatic class HystrixClientFallbackFactory implements FallbackFactory {
        @Override    public HystrixClient create(Throwable cause) {        
            return new HystrixClient() {
                @Override            
                public Hello iFailSometimes() {                
                    return new Hello("fallback; reason was: " + cause.getMessage());
                }
            };
        }
    }
    登入後複製
Feign支援繼承介面
  • Feign支援介面繼承的方式,將操作透過介面來形成契約。

    //生产者的控制层接口public interface UserService {
    
        @RequestMapping(method = RequestMethod.GET, value ="/users/{id}")
        User getUser(@PathVariable("id") long id);
    }
    //生产者的控制器实现
    @RestController
    public class UserResource implements UserService {}
    //消费端的Feign接口定义
    package project.user;
    @FeignClient("users")
    public interface UserClient extends UserService {}
    登入後複製

    壓縮支援
開啟壓縮可以有效節約網路資源,但是會增加CPU壓力,建議將最小壓縮的文件大小適度調大一點
    //开启压缩
    feign.compression.request.enabled=true
    feign.compression.response.enabled=true
    
    //配置压缩文档类型及最小压缩的文档大小
    feign.compression.request.mime-types=text/xml,application/xml,application/json
    feign.compression.request.min-request-size=2048
    登入後複製
  • 日誌配置


  • 消費服務的介面所在包,必須是debug
    • #

      # 日志支持logging.level.project.user.UserClient: DEBUG
      登入後複製

    • 定義自訂組態類別,定義日誌等級

    • @Configurationpublic class FooConfiguration {
          @Bean
          Logger.Level feignLoggerLevel() {        
              return Logger.Level.FULL;
          }
      }
      登入後複製
    • 日誌等級
    • #NONE, No logging (DEFAULT).# ########BASIC, Log only the request method and URL and the response status code and execution time.############HEADERS, Log the basic information along with request and response headers .############FULL, Log the headers, body, and metadata for both requests and responses.############

      以上是spring cloud2.0學習筆記之Feign實戰的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!