Spring Cloud 之 Feign 简介及简单DEMO的搭建

Feign简介:

Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign, 我们可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验。
Feign是在RestTemplate基础上封装的,使用注解的方式来声明一组与服务提供者Rest接口所对应的本地Java API接口方法。
Feign将远程Rest接口抽象成一个声明式的FeignClient(Java API)客户端,并且负责完成FeignClient客户端和服务提供方的Rest接口绑定。

整体目录:
Spring Cloud 之 Feign 简介及简单DEMO的搭建_第1张图片

feignconsumer消费方代码:

为了让Feign知道在调用方法时应该向哪个地址发请求以及请求需要带哪些参数,我们需要定义一个接口,Spring Cloud应用在启动时,Feign会扫描标有@FeignClient注解的接口,生成代理,并注册到Spring容器中。生成代理时Feign会为每个接口方法创建一个RequetTemplate对象,该对象封装了HTTP请求需要的全部信息,请求参数名、请求方法等信息都是在这个过程中确定的,Feign的模板化就体现在这里.

UserClient:

package com.tt.consumer.client;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * 有关消费者client,配置需要调用服务者的名字
 */
@FeignClient(name = "tt-sc-feign-provide") //对应的要调用提供者服务名spring.application.name
public interface UserClient {

    /**
     * 通过用户id获取用户
     * @param userId
     * @return
     */
    @GetMapping("/user/getUser/{userId}")//对应要调用提供者的controller
    String getUser(@PathVariable("userId") String userId);
}

FeignConsumerController

package com.tt.consumer.controller;

import com.tt.consumer.client.UserClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 平台controller业务逻辑,引入client出发消费者调用提供者
 */
@Api(tags = "用户模块")
@RestController
@RequestMapping("user")
public class FeignConsumerController {

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

    @Resource
    private UserClient userClient;

    /**
     * 通过用户ID获取用户
     * @param userId
     * @return
     */
    @ApiOperation(value = "根据用户ID查询用户")
    @GetMapping("/getUserInfo/{userId}")
    public String getUserInfo(@PathVariable("userId") String userId){

        String user = userClient.getUser(userId);
        return String.format("【%s-Demo消费者】:调用Feign接口返回值 %s", port, user);
    }

}

NacosFeignConsumerApplication

package com.tt.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
/**
 * 代表自己是一个服务消费者
 */
@SpringBootApplication
//声明此服务可作为消费者使用,配置feign客户端目录
@EnableFeignClients(basePackages = "com.tt.consumer.client")
public class NacosFeignConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(NacosFeignConsumerApplication.class, args);
    }
}

application-dev.yml未配置信息,bootstrap.yml如下:

server:
  port: 8083
spring:
  profiles:
    active: dev
  application:
    name: tt-sc-feign-consumer
  cloud:
    nacos:
      username: nacos
      password: nacos
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yml
      discovery:
        server-addr: 127.0.0.1:8848

pom.xml

<?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">
    <parent>
        <artifactId>springcloud</artifactId>
        <groupId>com.example</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>feignconsumer</artifactId>
<dependencies>
    <!-- 引入SpringCloud的Nacos server依赖 -->
    <!--服务发现pom-->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        <version>2.2.3.RELEASE</version>
    </dependency>

    <!-- feign -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        <version>2.2.3.RELEASE</version>
    </dependency>
   <dependency>
        <groupId>io.swagger</groupId>
        <artifactId>swagger-annotations</artifactId>
        <version>1.5.20</version>
        <scope>compile</scope>
    </dependency>

</dependencies>

</project>

feignprovide提供方代码

NacosFeignProvideApplication

package com.tt.feignprovide;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
 * 服务提供方-供feignclient使用
 **/
@EnableDiscoveryClient
@SpringBootApplication
public class NacosFeignProvideApplication {
    public static void main(String[] args) {
        SpringApplication.run(NacosFeignProvideApplication.class, args);
    }

}

UserProvideController

package com.tt.feignprovide.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "用户模块")
@RestController
@RequestMapping("user")
public class UserProvideController {

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

    /**
     * 通过用户ID获取用户
     * @param userId
     * @return
     */
    @ApiOperation(value = "根据用户ID查询用户")
    @GetMapping("/getUser/{userId}")
    public String getUser(@PathVariable("userId") String userId){

        return String.format("【%s-服务提供者】:%s", port, userId);
    }


}

application-dev.yml未配置信息,bootstrap.yml如下:

server:
  port: 8082
spring:
  profiles:
    active: dev
  application:
    name: tt-sc-feign-provide
  cloud:
    nacos:
      username: nacos
      password: nacos
      config:
        server-addr: 192.168.10.107:8848
        file-extension: yml
      discovery:
        server-addr: 192.168.10.107:8848

pom.xml

<?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">
    <parent>
        <artifactId>springcloud</artifactId>
        <groupId>com.example</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
<!--    <packaging>pom</packaging>-->
    <artifactId>feignprovide</artifactId>
    <dependencies>
        <!-- nacos 客户端 作为 注册与发现-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>
        <!-- nacos 配置中心 -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>
        <!-- feign 调用服务接口 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.2.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.20</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

</project>

父类pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>pom</packaging>
    <modules>
        <module>common</module>
        <module>manage</module>
        <module>tt-sc-generator</module>
        <module>feignprovide</module>
        <module>feignconsumer</module>
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
<!--        <version>2.1.8.RELEASE</version>-->
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springcloud</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springcloud</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring.boot.version>2.3.3.RELEASE</spring.boot.version>
        <spring.cloud.version>Hoxton.SR8</spring.cloud.version>
        <spring.cloud.sleuth.version>2.2.3.RELEASE</spring.cloud.sleuth.version>
        <swagger2.version>2.9.2</swagger2.version>
        <swagger-models.version>1.6.0</swagger-models.version>
        <swagger-annotations.version>1.6.0</swagger-annotations.version>
        <druid.starter.vsersion>1.1.21</druid.starter.vsersion>
        <commons.lang.version>2.4</commons.lang.version>
        <commons.lang3.version>3.7</commons.lang3.version>
        <commons.collections.version>3.2.1</commons.collections.version>
        <commons.io.version>2.6</commons.io.version>
        <spring.cloud.alibaba.version>2.1.2.RELEASE</spring.cloud.alibaba.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring.cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${spring.cloud.alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

测试结果:

Spring Cloud 之 Feign 简介及简单DEMO的搭建_第2张图片

Spring Cloud 之 Feign 简介及简单DEMO的搭建_第3张图片

你可能感兴趣的:(spring,cloud,spring,后端)