spring-cloud-feign案例

主要依赖

<dependencyManagement>
  <dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-netflix</artifactId>
        <version>1.0.7RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
<dependencies>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
  </dependency>
</dependencies>

FeignClient 代码

@FeignClient("bar-service")
public interface BarFeign{
  @RequestMapping(method = RequestMethod.GET ,value = "/bar" )
  String getBar();
}

@FeignClient("foo-service")
public interface FooFeign{
  @RequestMapping(method = RequestMethod.GET ,value = "/foo" )
  String getFoo();
}

App入口程序代码及调用FeignClient的代码

@RestController
@SpringBootApplication
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@EnableFeignClients
public class Application{

  @AutoWired
  FooFeign foo;

  @AutoWired
  BarFeign bar;

  @RequestMapping("/foo")
  public String foo(){
    return foo.getFoo();
  }
  @RequestMapping("/bar")
  public String bar(){
    return bar.getBar();
  }

  public static main(String[] args){
    SpringApplication.run(Application.class,args);
  }
}

测试可发现foo 和 bar 分别调用了foo-service 和bar-service服务
使用FeignClient可以使当前服务于其他服务更容易的集成

posted on 2016-03-02 14:49  laoniu85  阅读(3376)  评论(0编辑  收藏  举报

导航