上一篇博客咱們使用ribbon+restTemplate實現負載均衡調用服務,接下來咱們使用feign實現服務的調用,首先feign和ribbon的區別是什麼呢?java
ribbon根據特定算法,從服務列表中選取一個要訪問的服務;git
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