前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring Cloud 入门教程3、服务消费者(Feign)

Spring Cloud 入门教程3、服务消费者(Feign)

作者头像
KenTalk
发布2018-09-11 11:34:57
1.2K0
发布2018-09-11 11:34:57
举报
文章被收录于专栏:Ken的杂谈

一、前言

1、什么是Feign

Feign是基于Ribbon封装的HTTP Client工具包,Feign的目标是简化HTTP Client。Feign也确实做到了这一点,使用Feign发起HTTP请求只需要定义好接口并且配置好相应的注解即可完成对对应接口的绑定。

Spring Cloud基于Feign封装了Spring Cloud Feign(OpenFeign),同Ribbon一样,主要是方便结合Eureka、Consul等服务治理框架使用。Feign的主要作用是:从服务器端拿到对应服务列表后以负载均衡的方式访问对应服务,比Ribbon使用起来会更加方便。

从这张图上来说,Feign主要是从Eureka拿到服务列表之后,以负载均衡的策略选择其中一台发起调用。

2、本篇环境信息

框架

版本

Spring Boot

2.0.0.RELEASE

Spring Cloud

Finchley.BUILD-SNAPSHOT

JDK

1.8.x

3、准备工作

  • Eureka服务端搭建

参考:https://cloud.tencent.com/developer/article/1333816

  • 服务提供者搭建

参考:https://cloud.tencent.com/developer/article/1333816

说明

GroupId

io.ken.springcloud.testservice

ArtifactId

testservice

pom.xml、启动类(App.java)保持不变

二、服务提供者准备

1、配置Eureka地址

  • application.yml 配置
代码语言:javascript
复制
server:
  port: 8602

spring:
  application:
    name: testservice

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8800/eureka/

app:
  ip: localhost

2、DTO准备

  • 创建共用的ResponseDTO:Result.java
代码语言:javascript
复制
package io.ken.springcloud.testservice.model;

public class Result {

    private int code;

    private String message;

    private Object content;

    private String serviceName;

    private String host;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getContent() {
        return content;
    }

    public void setContent(Object content) {
        this.content = content;
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }
}
  • 创建Plus.java用作加法运算RequestDTO
代码语言:javascript
复制
package io.ken.springcloud.testservice.model;

public class Plus {

    private int numA;

    private int numB;

    public int getNumA() {
        return numA;
    }

    public void setNumA(int numA) {
        this.numA = numA;
    }

    public int getNumB() {
        return numB;
    }

    public void setNumB(int numB) {
        this.numB = numB;
    }
}

3、编写服务入口

  • 创建服务入口 TestController.java
代码语言:javascript
复制
package io.ken.springcloud.testservice.controller;

import io.ken.springcloud.testservice.model.Plus;
import io.ken.springcloud.testservice.model.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Value("${spring.application.name}")
    private String serviceName;

    @Value("${app.ip}")
    private String address;

    @Value("${server.port}")
    private String port;

    @RequestMapping("/")
    public Object index() {
        Result result = new Result();
        result.setServiceName(serviceName);
        result.setHost(String.format("%s:%s", address, port));
        result.setMessage("hello");
        return result;
    }

    @RequestMapping("/plus")
    public Object plus(Plus plus) {
        Result result = new Result();
        result.setServiceName(serviceName);
        result.setHost(String.format("%s:%s", address, port));
        result.setMessage("success");
        result.setContent(plus.getNumA() + plus.getNumB());
        return result;
    }

    @RequestMapping("/plus2")
    public Object plus2(@RequestBody Plus plus) {
        Result result = new Result();
        result.setServiceName(serviceName);
        result.setHost(String.format("%s:%s", address, port));
        result.setMessage("success");
        result.setContent(plus.getNumA() + plus.getNumB());
        return result;
    }

}

4、访问测试

  • 启动TestService

分别以端口8602,8603启动testservice。

此时testservice等于是在Eureka Server注册了两个实例

分别访问 http://localhost:8602,http://localhost:8603

将会看到以下信息:

代码语言:javascript
复制
# http://localhost:8602
{
  "code": 0,
  "message": "success",
  "content": 0,
  "serviceName": "testservice",
  "host": "localhost:8062"
}

# http://localhost:8603
{
  "code": 0,
  "message": "success",
  "content": 0,
  "serviceName": "testservice",
  "host": "localhost:8063"
}

三、服务消费者搭建(Feign)

1、创建Feign项目

  • 创建一个Spring Boot工程

使用maven-archtype-quickstart模板创建项目

说明

GroupId

io.ken.springcloud.feignclient

ArtifactId

feignclient

  • 在pom.xml加入相关依赖
代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>io.ken.springcloud.feignclient</groupId>
    <artifactId>feignclient</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>feignclient</name>
    <url>http://ken.io</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.BUILD-SNAPSHOT</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/libs-snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <build>
        <finalName>feignclient</finalName>
    </build>

</project>

2、配置Fegin启动类

  • 配置启动类

修改\src\main\java\io\ken\springcloud\eurekaserver\App.java

基于Spring Boot创建启动类,添加上 @EnableDiscoveryClient 注解

另外也需要增加 @EnableFeignClients 注解

代码语言:javascript
复制
package io.ken.springcloud.feignclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class App {

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

}

3、DTO准备

  • 创建共用的ResponseDTO:Result.java
代码语言:javascript
复制
package io.ken.springcloud.feignclient.model;

public class Result {

    private int code;

    private String message;

    private Object content;

    private String serviceName;

    private String host;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getContent() {
        return content;
    }

    public void setContent(Object content) {
        this.content = content;
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }
}
  • 创建Plus.java作为加法运算RequestDTO
代码语言:javascript
复制
package io.ken.springcloud.feignclient.model;

public class Plus {

    private int numA;

    private int numB;

    public int getNumA() {
        return numA;
    }

    public void setNumA(int numA) {
        this.numA = numA;
    }

    public int getNumB() {
        return numB;
    }

    public void setNumB(int numB) {
        this.numB = numB;
    }
}

4、编写Eureka服务访问

  • 创建TestService.java
代码语言:javascript
复制
package io.ken.springcloud.feignclient.service;

import io.ken.springcloud.feignclient.model.Plus;
import io.ken.springcloud.feignclient.model.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@FeignClient(value = "testservice")
public interface TestService {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    String indexService();

    @RequestMapping(value = "/plus", method = RequestMethod.GET)
    Result plusService(@RequestParam(name = "numA") int numA, @RequestParam(name = "numB") int numB);

    @RequestMapping(value = "/plus", method = RequestMethod.POST, consumes = "application/json")
    Result plusabService(Plus plus);

    @RequestMapping(value = "/plus2", method = RequestMethod.POST)
    Result plus2Service(@RequestBody Plus plus);


}

5、编写服务入口

创建 TestController.java 作为访问testservice的入口

代码语言:javascript
复制
package io.ken.springcloud.feignclient.controller;

import io.ken.springcloud.feignclient.model.Plus;
import io.ken.springcloud.feignclient.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @RequestMapping("/")
    public Object index() {
        return "feign client";
    }

    @RequestMapping("/ti")
    public Object ti() {
        return testService.indexService();
    }

    @RequestMapping("/plus")
    public Object plus(@RequestParam("numa") int numA, @RequestParam("numb") int numB) {
        return testService.plusService(numA, numB);
    }

    @RequestMapping("/plusab")
    public Object plusA(@RequestParam("numa") int numA, @RequestParam("numb") int numB) {
        Plus plus = new Plus();
        plus.setNumA(numA);
        plus.setNumB(numB);
        return testService.plusabService(plus);
    }

    @RequestMapping("/plus2")
    public Object plus2(Plus plus) {
        return testService.plus2Service(plus);
    }


}

6、配置Eureka Client

在\src\main下创建文件夹resources文件夹并设置为Resources Root

在resources文件夹下创建application.yml文件并配置Eureka Client

代码语言:javascript
复制
server:
  port: 8605

spring:
  application:
    name: feignclient

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8800/eureka/

7、服务消费/访问测试

FeignClient项目启动后,访问 http://localhost:8605/ti

会交替显示以下内容

代码语言:javascript
复制
{
  "code": 0,
  "message": "hello",
  "content": null,
  "serviceName": "testservice",
  "host": "localhost:8602"
}

{
  "code": 0,
  "message": "hello",
  "content": null,
  "serviceName": "testservice",
  "host": "localhost:8603"
}

也可以分别访问

http://localhost:8605/plus?numa=1&numb=2

http://localhost:8605/plusab?numa=1&numb=2

http://localhost:8605/plus2?numA=1&numB=2

测试不同的传参方式

四、备注

  • 本篇示例代码

https://github.com/ken-io/springcloud-course/tree/master/chapter-03

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018/04/19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、前言
    • 1、什么是Feign
      • 2、本篇环境信息
        • 3、准备工作
        • 二、服务提供者准备
          • 1、配置Eureka地址
            • 2、DTO准备
              • 3、编写服务入口
                • 4、访问测试
                • 三、服务消费者搭建(Feign)
                  • 1、创建Feign项目
                    • 2、配置Fegin启动类
                      • 3、DTO准备
                        • 4、编写Eureka服务访问
                          • 5、编写服务入口
                            • 6、配置Eureka Client
                              • 7、服务消费/访问测试
                              • 四、备注
                              相关产品与服务
                              负载均衡
                              负载均衡(Cloud Load Balancer,CLB)提供安全快捷的四七层流量分发服务,访问流量经由 CLB 可以自动分配到多台后端服务器上,扩展系统的服务能力并消除单点故障。轻松应对大流量访问场景。 网关负载均衡(Gateway Load Balancer,GWLB)是运行在网络层的负载均衡。通过 GWLB 可以帮助客户部署、扩展和管理第三方虚拟设备,操作简单,安全性强。
                              领券
                              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档