SpringCloud學習筆記(6、SpringCloud Netflix Feign)

目錄:

  • feign簡介
  • feign應用

feign簡介:

feign是一款Netflix開源的聲明式、模板化的http客戶端,它能夠更加便捷、優雅的調用http api;SpringCloud對Netflix的feign進行了加強,使其支持spring並整合了ribbon、eureka以提供負載均衡的http調用。spring

feign應用:

一、引入openfeign依賴api

1 <dependency>
2     <groupId>org.springframework.cloud</groupId>
3     <artifactId>spring-cloud-starter-openfeign</artifactId>
4 </dependency>

二、啓動類加上feign註解(須要eureka的支持,因此此模塊首先須要爲eureka客戶端)app

)第一種,針對類掃描feign api負載均衡

@EnableFeignClients(clients = {Xxx1.class, Xxx2.class})spa

)第二種,針對包掃描feign apicode

@EnableFeignClients(basePackages = {"com.xxx.xxx"})blog

三、定義feign api接口

feign api只需與模塊的api保持一致就能夠了get

)模塊:模板

1 @RestController 2 @RequestMapping("/ad") 3 public class AdApi { 4 
5     @GetMapping("/getUserAd/{account}") 6     public String getUserAd(@PathVariable(name = "account") String account) { 7         return "這是" + account + "的廣告"; 8  } 9 }

)feign api:

1 @FeignClient(name = "ad-model") 2 public interface AdRemoteService { 3 
4     @GetMapping("/ad/getUserAd/{account}") 5     String getUserAd(@PathVariable(name = "account") String account); 6 }

四、調用

調用方式很簡單,就像調用方法同樣就能夠了

 1 @Autowired  2 private AdRemoteService adRemoteService;  3 
 4 @GetMapping("/login/{account}/{password}")  5 public String login(@PathVariable String account, @PathVariable String password) {  6     UserDTO userDTO = USER_INFO.get(account);  7     if (userDTO == null) {  8         return "FAILED";  9  } 10 
11     boolean result = userDTO.getPassword().equalsIgnoreCase(password); 12     if (!result) { 13         return "FAILED"; 14  } 15 
16     // 調用廣告接口
17     String adResult = adRemoteService.getUserAd(account); 18  System.err.println(adResult); 19 
20     return "SUCCESS"; 21 }
相關文章
相關標籤/搜索