Spring Cloud (5) —— Feign 調用 provider 和 負載均衡

關於 Feign

Feign是一個聲明式的僞Http客戶端,它使得 Http 客戶端編碼變得更簡單。使用Feign,只須要建立一個接口並註解。它具備可插拔的註解特性,可以使用Feign 註解和 JAX-RS 註解。Feign 支持可插拔的編碼器和解碼器。Feign 默認集成了 Ribbon,天然就實現了負載均衡的效果。web

Feign 的使用

  1. 新建模塊 spring-cloud.s04.store-feign
  2. pom 中添加依賴spring

    <dependencies>
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
      </dependencies>
  3. 添加配置文件
    application.ymlapp

    server:
      port: 31002
    spring:
      application:
        name: store-feign
    eureka:
      client:
        serviceUrl:
          defaultZone: http://user:123123@localhost:34001/eureka/
      instance:
        instance-id: ${spring.cloud.client.ip-address}:${server.port}/${spring.application.name}
        prefer-ip-address: true
        lease-renewal-interval-in-seconds: 10
        lease-expiration-duration-in-seconds: 30
  4. 建立啓動類 ..StoreFeign負載均衡

    @SpringBootApplication
    @EnableEurekaClient
    @EnableFeignClients
    public class StoreFeign {
      public static void main(String[] args) {
        SpringApplication.run(StoreFeign.class, args);
      }
    }
  5. 爲了專一 Feign 的使用,將 Feign 的應用提取到 service 層,與 controller 層的註解分開。建立接口 ..StoreFeignServiceide

    /*
    @FeignClient("") 參數填 Spring Cloud Provider 的應用名 ${spring.application.name}
     */
    @FeignClient("album-provider")
    public interface StoreFeignService {
      /*
      @RequestMapping() 默認參數是請求資源的地址,
      也能夠指定請求的 Http Method @RequestMapping(value="/movie/movies",method=RequestMethod.GET)
    
      getMovies() 也能夠算入參數,例如 getMovies(@RequestParam("name") String name) ,調用時好比傳入的參數
       */
      @RequestMapping("/album/server-port")
      public String getProviderPort();
    }
  6. 建立訪問入口 ..StoreFeignControllerspring-boot

    @RestController
    @RequestMapping("/store-feign")
    public class StoreFeignController {
    
      @Autowired
      StoreFeignService storeFeignService;
    
      @RequestMapping("/album-provider-port")
      public String getProviderPort() {
        return storeFeignService.getProviderPort();
      }
    }
  7. 啓動項目,訪問 http://localhost:31002/store-feign/album-provider-port ,屢次刷新,能夠發現負載均衡策略是輪訓。 Feign 就是使用 Ribbon 的負載均衡策略,固然改變負載均衡策略的方法就與 Ribbon 的方法相同。

壓縮傳輸數據

相關文章
相關標籤/搜索