SpringCloud Feign 配置(基於Consul)


一.基礎配置

  1.引入依賴

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
       
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>

 

   2.創建主類,通過 @EnableFeginClients 注解開啟 Feign 功能

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class Application {

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

    3.定義AService接口,通過 @FeignClient 注解指定服務名來綁定服務, 然后使用SpringMVC 的注解來綁定具體該服務提供的 REST 接口

@FeignClient("aservice")  //這里的服務名不區分大小寫
public interface AService {
    @PostMapping("/hello")
    String hello();
}

    需要調用 AService 時,在類中使用 @Autowired 注解直接注入 AService 實例, 並調用 /hello 接口

@RestController
public class ConsumerController {

    @Autowired
    private AService aService;

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

 

二.參數綁定

@FeignClient("aservice") 
public interface AService {  
  @RequestMapping("/hello1")
   String hello1(@RequestParam("hello1") String hello1); 
  @RequestMapping("/hello2") 
  String hello2(@RequestHeader("hello2") String hello2)
  @RequestMapping("/hello3") 
  String hello2(@RequestBody User user)
}

 

   

@RestController
public class BController{  
  @RequestMapping(value = "/hello1", method = RequestMethod.GET)
   String hello1(@RequestParam String hello1){
    return "hello";
  }
  @RequestMapping(value =
"/hello2", method = RequestMethod.GET)   
  String hello2(@RequestHeader String hello2){
    return "hello";
  }
  
  @RequestMapping(value =
"/hello3", method = RequestMethod.POST)   
  String hello3(@RequestBody User user){
    return "hello";
  }
}

 

三.Ribbon 配置

  由於 Feign 的客戶端負載均衡是通過 Ribbon 實現的, 所以可以通過配置 Ribbon 客戶端的方式來自定義各個服務客戶端調用的參數.

  1.全局配置

    全局配置直接使用 ribbon.<key>=<value>的方式來設置 ribbon 的各項默認參數. 比如, 修改默認的客戶端調用超時時間:  

ribbon.ReadTimeout=5000
ribbon.ConnectTimeout=500

   2.指定服務配置

     大多數情況下, 服務調用的超時時間會根據實際服務的特性做一些調整, 所以需要指定服務配置

     指定服務配置根據 <client>.ribbon.key=value 的格式進行配置

aservice.ribbon.ReadTimeout=2000
aservice.ribbon.ConnectTimeout=500

    3.重試機制

ribbon.MaxAutoRetries=1
ribbon.MaxAutoRetriesNextServer=2

 

     MaxAutoRetries 設置為1, 所以重試策略先嘗試訪問首選實例一次,失敗后才會更換實例訪問,而更換實例訪問的次數通過 MaxAutoRetriesNextServer 參數設置為2, 所以會嘗試更換兩次實例進行重試.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM