spring cloud 的Feign 的基本操作

1、
引包

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2、主類 加Feign客戶端 @EnableFeignClients註解開啓Feign的功能

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceFeignApplication {

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

3、service 定義一個feign接口,通過@ FeignClient(“服務名”),來指定調用哪個服務。

@FeignClient(value = "service-helloworld")
public interface HelloWorldService {

    @RequestMapping(value = "/",method = RequestMethod.GET)
    String sayHello();
}

conller調用

public class WebController {

    @Autowired
    HelloWorldService helloworldservice;

    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String sayHello(){
        return helloworldservice.sayHello();
    }
}

  1. Feign在默認情況下使用的是JDK原生的URLConnection發送HTTP請求,沒有連接池,但是對每個地址gwai會保持一個長連接,即利用HTTP的persistence
    connection 。我們可以用Apache的HTTP Client替換Feign原始的http client,
    從而獲取連接池、超時時間等與性能息息相關的控制能力。Spring
    Cloud從Brixtion.SR5版本開始支持這種替換,首先在項目中聲明Apache HTTP
    Client和feign-httpclient依賴:
<!-- 使用Apache HttpClient替換Feign原生httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>com.netflix.feign</groupId>
            <artifactId>feign-httpclient</artifactId>
            <version>${feign-httpclient}</version>
        </dependency>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章