上一篇博客我們使用ribbon+restTemplate實現負載均衡調用服務,接下來我們使用feign實現服務的調用,首先feign和ribbon的區別是什么呢?
ribbon根據特定算法,從服務列表中選取一個要訪問的服務;
- RoundRobinRule:輪詢
- RandomRule:隨機
- AvailabilityFilteringRule: 會先過濾掉由於多次訪問故障而處於斷路器跳閘狀態的服務,以及並發的連接數量,超過閾值的服務,然后對剩余的服務列表按照輪詢策略進行訪問;
- WeightedResponseTimeRule: 根據平均響應時間計算所有服務的權重,響應時間越快,服務權重越大,被選中的機率越高,剛啟動時,如果統計信息不足,則使用RoundRobinRule策略,等統計信息足夠時,會切換到WeightedResponseTimeRule
- RetryRule: 先按照RoundRobinRule的策略獲取服務,如果獲取服務失敗,則在指定時間內會進行重試,獲取可用的服務;
- BestAvailableRule: 會先過濾掉由於多次訪問故障而處於斷路器跳閘狀態的服務,然后選擇一個並發量最小的服務;
- ZoneAvoidanceRule: 默認規則,復合判斷server所在區域的性能和server的可用性選擇服務器;
Spring Cloud Netflix 的微服務都是以 HTTP 接口的形式暴露的,所以可以用 Apache 的 HttpClient 或 Spring 的 RestTemplate 去調用, Feign 是一個使用起來更加方便的 HTTP 客戶端,使用起來就像是調用自身工程的方法,而感覺不到是調用遠程方法。接下來我們簡單使用一下Feign:
前提:有兩個服務,一個movie,一個user,user運行在多個端口(模擬多台機器部署服務)。
首先引入Feign依賴
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
第二步:在movie服務中寫一個接口UserInterface.java,調用user服務,接口代碼如下:
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"})指定上面接口所在的類,可以只到父包
第四步:在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/SpringCloud