SpringCloud Feign 配置(基於Consul)

一.基礎配置web

  1.引入依賴spring

     <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 功能app

@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 接口spring-boot

@RestController
public class ConsumerController {

    @Autowired
    private AService aService;

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

 

二.參數綁定spa

@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 配置code

  因爲 Feign 的客戶端負載均衡是經過 Ribbon 實現的, 因此能夠經過配置 Ribbon 客戶端的方式來自定義各個服務客戶端調用的參數.blog

  1.全局配置接口

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

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, 因此會嘗試更換兩次實例進行重試.

相關文章
相關標籤/搜索