springCloud-Feign的使用

一、簡介:

Feign是一個聲明式的Rest 客戶端,它能讓Rest調用更加簡單。Feign提供Http的請求模板,通過編寫簡單的接口和插入的註解,就可以定義好Http請求的參數,格式,地址信息,Feign 則會完全代理Http請求,我們只需要向調用方法一樣調用它就可以完成服務請求及相關處理。SpringCloud 對Feign進行了封裝,使其支持 springMvc標準註解和HttpMessageConverters。Feign可以與Eureka 和Ribbon 組合使用以支持負載均衡。

二、Feign的使用

1. 引入依賴

   <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.2.RELEASE</version>
        </dependency>

2. 在啓動類上加註解 @EnableFeignClients

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.example.ribbon.ribbon.fegin")
public class RibbonApplication {

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

}

3. 使用Feign調用接口

@FeignClient(value = "eureka-client-user-service",configuration = FeignConfiguration.class)
public interface UserRemoteClient {

    @GetMapping("/user/helloToPerson")
    String sayHelloToPerson(@RequestParam("userName") String userName);
}

提供服務的接口是這樣的


    @GetMapping("/user/helloToPerson")
    public String sayHelloToPerson(@RequestParam("userName") String userName){
        return myService.sayHelloToPerson(userName);
    }

@FeignClient中的eureka-client-user-service就是你要調用的服務的名字

@FeignClient中的 FeignConfiguration.class 就是寫Feign配置信息的類名

@FeignClient 註解的作用:它標識當前是一個Feign的客戶端,Value屬性是對應的服務名稱,也就是你需要調用哪個服務中的接口。

4. controller層的調用

@RestController
public class UserController {

    private MyService myService;

    @Autowired
    public UserController(MyService myService){
        this.myService = myService;
    }


    @GetMapping("/user/helloToPerson")
    public String sayHelloToPerson(@RequestParam("userName") String userName){
        return myService.sayHelloToPerson(userName);
    }
}

三、自定義Feign的配置

@Configuration
public class FeignConfiguration {

    /**
     * 日誌級別的配置
     * @return
     */
    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.NONE;
    }

    /**
     * basic認證配置
     * @return
     */
    @Bean
    public BasicAuthenticationInterceptor basicAuthenticationInterceptor(){
        return new BasicAuthenticationInterceptor("user","password");
    }

    /**
     * 配置超時時間
     * @return
     */
    @Bean
    public Request.Options options(){
        return new Request.Options(5000,10000);
    }


}

寫好這個類之後,要在@FeignClient 的註解中加入 configuration = FeignConfiguration.class

四、GZIP壓縮配置

可以在配置文件中加入如下配置:

#gzip壓縮配置
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

 

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