spring cloud中声明式REST调用Feign

spring cloud中声明式REST调用Feign

文章目录

  • spring cloud中声明式REST调用Feign
      • 一、简介
      • 二、步骤
        • 2.1 Feign使用步骤
        • 2.2 添加熔断步骤
      • 三、示例
        • 3.1 注册中心
          • 3.1.1 maven依赖
          • 3.1.2 application.yaml配置
          • 3.1.3 启动类
        • 3.2 服务
          • 3.2.1 maven依赖
          • 3.2.2 application.yaml配置
          • 3.2.3 服务相关类
        • 3.3 客户端
          • 3.3.1 maven依赖
          • 3.3.2 application.yaml配置
          • 3.3.3 调用相关类
        • 4.4 测试

一、简介

Feign是Netflix开发的声明式、模板化http客户端,简化了对http的调用。同时Feign带有负载均衡策略及熔断策略,这里对其使用进行介绍。

二、步骤

2.1 Feign使用步骤

开启Feign步骤如下:

  1. 添加核心maven依赖:

    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-openfeignartifactId>
    dependency>
    
  2. 启动类添加支持feign的注解@EnableFeignClients;

  3. 添加调用接口,并用注解@FeignClient修饰,注解内value值指定调用的服务名;

  4. 在上一步调用接口中,添加调用服务方法,用注解@RequestMapping修饰,注解内指定服务路径。服务方法参数用@RequestParam修饰;

  5. 在实用中,直接使用调用接口方法即可;

这里就完成了基本的feign使用步骤。

2.2 添加熔断步骤

熔断即当服务不可用时,提供的服务策略,在完成2.1中的所有步骤后,开启熔断还需步骤如下:

  1. application.yaml中添加开启熔断配置:

    feign:
      hystrix:
        enabled: true #feign添加支持熔断处理
    
  2. 添加熔断服务,即添加实现类,实现调用接口;

  3. 调用接口注解@FeignClient中属性fallback指定熔断服务类实例;

三、示例

这里使用注册中心spring_cloud_register_center、服务spring_cloud_provider、客户端spring_cloud_client_feign进行示例。

3.1 注册中心

注册中心为spring_cloud_register_center项目。

3.1.1 maven依赖

<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.2.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.dragon.studygroupId>
    <artifactId>spring_cloud_register_centerartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>spring_cloud_register_centername>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
        <spring-cloud.version>Hoxton.SR6spring-cloud.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>
3.1.2 application.yaml配置
server:
  port: 8010
spring:
  application:
    name: spring-cloud-register-center
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:${server.port}/eureka/
    fetchRegistry: false #是否拉取注册信息,由于注册中心是单个结点,不需要拉取
    registerWithEureka: false #是否注册自己,由于当前就是注册中心,帮不需要注册
3.1.3 启动类
package com.dragon.study.spring_cloud_register_center;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class SpringCloudRegisterCenterApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudRegisterCenterApplication.class, args);
    }
}

3.2 服务

服务为spring_cloud_provider项目。

3.2.1 maven依赖

<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.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.2.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.dragon.studygroupId>
    <artifactId>spring_cloud_providerartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>spring_cloud_providername>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
        <spring-cloud.version>Hoxton.SR6spring-cloud.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.6version>
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
    dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>
3.2.2 application.yaml配置
server:
  port: 8011
spring:
  application:
    name: spring-cloud-provider
eureka:
  instance:
    prefer-ip-address: true #true表示使用ip注册,若为false,则表示使用系统hostname注册
  client:
    service-url:
      default-zone: http://localhost:8010/eureka/
management:
  endpoints:
    web:
      exposure:
        include: "*"
3.2.3 服务相关类

定义实体bean类Stu.java

package com.dragon.study.spring_cloud_provider.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Stu {
    private String stuId;
    private  Integer age;
}

定义服务controller类StuController.java

package com.dragon.study.spring_cloud_provider.controller;
import com.dragon.study.spring_cloud_provider.bean.Stu;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("stu")
public class StuController {
    @RequestMapping("getStu")
    private Object getStu(Stu stu) {
        System.out.println(stu);
        return stu;
    }
}

定义启动类SpringCloudProviderApplication.java

package com.dragon.study.spring_cloud_provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudProviderApplication.class, args);
    }
}

3.3 客户端

3.3.1 maven依赖

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.2.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.dragon.studygroupId>
    <artifactId>spring_cloud_client_feignartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>spring_cloud_client_feignname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
        <spring-cloud.version>Hoxton.SR6spring-cloud.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloudgroupId>
                <artifactId>spring-cloud-dependenciesartifactId>
                <version>${spring-cloud.version}version>
                <type>pomtype>
                <scope>importscope>
            dependency>
        dependencies>
    dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>
project>
3.3.2 application.yaml配置
server:
  port: 8052
spring:
  application:
    name: spring-cloud-feign-client
eureka:
  instance:
    preferIpAddress: true #true表示使用ip注册,若为false,则表示使用系统hostname注册
  client:
    serviceUrl:
      defaultZone: http://localhost:8010/eureka/
feign:
  hystrix:
    enabled: true #feign添加支持熔断处理
3.3.3 调用相关类
  1. 定义实体类:
package com.dragon.study.spring_cloud_feign_client.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Stu {
    private String stuId;
    private  Integer age;
}
  1. 定义启动类:
package com.dragon.study.spring_cloud_feign_client;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients
public class SpringCloudFeignClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudFeignClientApplication.class, args);
    }
}
  1. 定义调用接口:
package com.dragon.study.spring_cloud_feign_client.service;
import com.dragon.study.spring_cloud_feign_client.bean.Stu;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(value = "spring-cloud-provider", fallback = StuServiceHystrix.class)
public interface StuServiceFeign {
    @RequestMapping("/stu/getStu")
    Stu getStu(@RequestParam String stuId, @RequestParam Integer age);
}
  1. 定义熔断服务实现类:
package com.dragon.study.spring_cloud_feign_client.service;
import com.dragon.study.spring_cloud_feign_client.bean.Stu;
import org.springframework.stereotype.Service;
@Service
public class StuServiceHystrix implements StuServiceFeign {
    //远程服务不可用时调用此实现
    @Override
    public Stu getStu(String stuId, Integer age) {
        return new Stu("000",18);
    }
}
  1. 定义controller:
package com.dragon.study.spring_cloud_feign_client.controller;
import com.dragon.study.spring_cloud_feign_client.bean.Stu;
import com.dragon.study.spring_cloud_feign_client.service.StuServiceFeign;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("stu")
public class StuController {
    @Resource
    private StuServiceFeign stuServiceFeign;
    @RequestMapping("getStu")
    public Object getStu(Stu stu) {
        return stuServiceFeign.getStu(stu.getStuId(), stu.getAge());
    }
}

4.4 测试

依次启动注册中心spring_cloud_register_center、服务spring_cloud_provider(启动多个实例,端口不同,服务名一样)、客户端spring_cloud_client_feign。

常规测试:

#在客户端多次调用服务,可获取正常结果,且服务端多个实例均有调用
GET http://localhost:8052/stu/getStu?stuId=001&age=17
Accept: application/json

上面正常输出如下:

{
  "stuId": "001",
  "age": 17
}

熔断测试,停掉所有服务,再次调次,输出为:

{
  "stuId": "000",
  "age": 18
}

你可能感兴趣的:(微服务)