分享

spring-cloud(三)声明性REST客户端[Feign]

 关平藏书 2018-01-12

这篇文章介绍下spring-cloud声明性REST客户端[Feign]

先看下官方文档的描述

1.png

本案例在将spring-cloud(一)服务的注册与发现中的eureka及server案例基础上进行改造。

1.创建一个spring-boot项目 tm-service-feign

2.在pom文件中增加feign依赖支持

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-feign</artifactId>
  4. </dependency>

3.在application.yml中增加eureka注册中心,及服务名称

  1. eureka:
  2. client:
  3. serviceUrl:
  4. defaultZone: http://localhost:8761/eureka/
  5. server:
  6. port: 8765
  7. spring:
  8. application:
  9. name: service-feign

4.在启动类上增加注解 @EnableFeignClients

  1. @SpringBootApplication
  2. @EnableDiscoveryClient
  3. @EnableFeignClients
  4. public class ServiceFeignApplication {
  5. public static void main(String[] args) {
  6. SpringApplication.run(ServiceFeignApplication.class, args);
  7. }
  8. }

5.创建service接口,在类上增加 @FeignClient

  1. @FeignClient(value = "service")
  2. public interface IHelloService {
  3. @RequestMapping(value = "/hello", method = RequestMethod.GET)
  4. String hello(@RequestParam(value = "name") String name);
  5. }

6.创建controller使用service调用远程服务

  1. @RestController
  2. public class HelloController {
  3. @Autowired
  4. IHelloService helloService;
  5. @RequestMapping(value = "/hello", method = RequestMethod.GET)
  6. public String hello(@RequestParam(name = "name", defaultValue = "皇太极") String name) {
  7. return helloService.hello(name);
  8. }
  9. }

7.分别启动tm-eureka-server,tm-service(修改端口8763再启动一次),tm-service-feign

8.浏览器访问
http://localhost:8761/

2.png

访问 http://localhost:8765/hello

3.png

4.png

此时可以发现tm-service-feign服务正常调用到tm-service提供的服务,并且可以观察到端口是8762和8763交替出现的,说明已经完成了负载均衡的效果。
因为Feign默认集成了Ribbon,并和Eureka结合,默认实现了负载均衡的效果。
这个原理和源码部分后续会再解释。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多