上一篇博客咱们使用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