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<Store> getStores(); @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json") Store update(@PathVariable("storeId") Long storeId, Store store); }
# To disable Hystrix in Feignfeign: hystrix: enabled: true# To set thread isolation to SEMAPHORE# 将断路器隔离级别由默认的线程隔离调整为信号灯hystrix: command: default: execution: isolation: strategy: SEMAPHORE
@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<HystrixClient> { @Override public HystrixClient create(Throwable cause) { return new HystrixClient() { @Override public Hello iFailSometimes() { return new Hello("fallback; reason was: " + cause.getMessage()); } }; } }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 {}壓縮支援
//开启压缩 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
#
# 日志支持logging.level.project.user.UserClient: DEBUG
@Configurationpublic class FooConfiguration { @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } }
以上是spring cloud2.0學習筆記之Feign實戰的詳細內容。更多資訊請關注PHP中文網其他相關文章!