Feign實現服務調用

 上一篇博客咱們使用ribbon+restTemplate實現負載均衡調用服務,接下來咱們使用feign實現服務的調用,首先feign和ribbon的區別是什麼呢?java

  ribbon根據特定算法,從服務列表中選取一個要訪問的服務;git

  1. RoundRobinRule:輪詢
  2. RandomRule:隨機
  3. AvailabilityFilteringRule: 會先過濾掉因爲屢次訪問故障而處於斷路器跳閘狀態的服務,以及併發的鏈接數量,超過閾值的服務,而後對剩餘的服務列表按照輪詢策略進行訪問;
  4. WeightedResponseTimeRule: 根據平均響應時間計算全部服務的權重,響應時間越快,服務權重越大,被選中的機率越高,剛啓動時,若是統計信息不足,則使用RoundRobinRule策略,等統計信息足夠時,會切換到WeightedResponseTimeRule
  5. RetryRule: 先按照RoundRobinRule的策略獲取服務,若是獲取服務失敗,則在指定時間內會進行重試,獲取可用的服務;
  6. BestAvailableRule: 會先過濾掉因爲屢次訪問故障而處於斷路器跳閘狀態的服務,而後選擇一個併發量最小的服務;
  7. ZoneAvoidanceRule: 默認規則,複合判斷server所在區域的性能和server的可用性選擇服務器;

     Spring Cloud Netflix 的微服務都是以 HTTP 接口的形式暴露的,因此能夠用 Apache 的 HttpClient 或 Spring 的 RestTemplate 去調用, Feign 是一個使用起來更加方便的 HTTP 客戶端,使用起來就像是調用自身工程的方法,而感受不到是調用遠程方法。接下來咱們簡單使用一下Feign:github

前提:有兩個服務,一個movie,一個user,user運行在多個端口(模擬多臺機器部署服務)。web

 首先引入Feign依賴算法

  

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

第二步:在movie服務中寫一個接口UserInterface.java,調用user服務,接口代碼以下:spring

package com.xing.movie.FeignInteface;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.xing.movie.entity.User;

@FeignClient("xing-user")//服務名
public interface UserInterface {

    @RequestMapping(value ="/user/findByNameEn/{nameEn}" ,method =RequestMethod.GET )//必須使用RequestMapper,使用GetMapping啓動報錯
    public User findByNameEn(@PathVariable("nameEn") String nameEn);//@PathVariable後面須要指定nameEn,否則可能報錯
    
}

第三步:在啓動類中添加註解@EnableFeignClients(basePackages = {"com.xing.movie"})指定上面接口所在的類,能夠只到父包json

第四步:在MovieController中調用上面寫的接口服務器

@Autowired
private UserInterface userInterface;
@ApiOperation(value
= "查詢用戶", notes = "查詢用戶By英文名")//方法說明 @ApiResponses(value = {@ApiResponse(code = 200, message = "成功", response = Movie.class)})//響應數聽說明,能夠有多個 @ApiImplicitParam(name = "nameEn", value = "用戶英文名", paramType = "path", required = true, dataType = "String") @GetMapping(value = "/findUserByNameEn/{nameEn}",produces = { "application/json;charset=UTF-8" }) public User findUserByNameEn(@PathVariable String nameEn) { User user = userInterface.findByNameEn(nameEn); System.out.println("findUserByNameEn----"+user); return user; }

以後直接訪問測試,ok!併發

 源碼地址:https://github.com/OnlyXingxing/SpringCloudapp

相關文章
相關標籤/搜索