7.1 Feign的簡介
7.2 Feign使用
7.2.1 導入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
7.2.2 配置調用接口
package xx.study.sc.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
/**聲明需要調用的微服務名稱
* @FeignClient
* name:服務提供者的名稱
*
*/
@FeignClient(name="service-product")
public interface ProductFeignClient {
/**
* 配置需要調用的微服務接口
* 訪問路徑要寫全 類+方法
*/
@RequestMapping(value = "/product/buy",method = RequestMethod.GET)
public String buy(@RequestParam String name);
}
7.2.3 在啓動類上激活Feign
package xx.study.sc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableFeignClients
public class OrderApplication {
/**
* 使用spring 提供的RestTemplate發送http請求到商品服務
* 1。創建RestTemplate對象交給容器管理
* 2。在使用的時候,調用其方法完成操作
*
*/
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class);
}
}
7.2.4 通過自動的接口調用遠程服務
package xx.study.sc.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import xx.study.sc.feign.ProductFeignClient;
import java.util.List;
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private ProductFeignClient productFeignClient;
@RequestMapping(value = "/buyBanana",method = RequestMethod.GET)
public String buyBanana(@RequestParam String name){
name=productFeignClient.buy(name);
String returnVal="從feign收到"+name+"!!!";
return returnVal;
}
}
7.3 支持負載均衡
7.4 Feign和Ribbon的聯繫
7.5 請求壓縮
7.6 日誌設置
7.7 源碼