Skip to content

Latest commit

 

History

History
384 lines (276 loc) · 9.99 KB

File metadata and controls

384 lines (276 loc) · 9.99 KB

Spring Cloud Alibaba 2.2 服务消费者(Feign)


1 摘要

Feign 是微服务之间相互调用使用最广泛的工具,其内部集成了 Ribbon ,直接在接口上使用注解,极大地简化了微服务的调用过程。本文将介绍基于 Spring Cloud Alibaba 2.2 搭建使用 Feign 的服务消费者。

2 核心 Maven 依赖

./cloud-alibaba-server-consumer-feign/pom.xml
    <dependencies>
        <!-- cloud alibaba -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>${spring-cloud-alibaba.version}</version>
        </dependency>
        <!-- cloud feign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>${spring-cloud-openfeign.version}</version>
        </dependency>
        
        <!-- 省略其他依赖 -->

    </dependencies>

    <dependencyManagement>
        <dependencies>
            <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>
    </dependencyManagement>

其中 ${spring-cloud-alibaba.version} 的版本为 2.2.3.RELEASE , ${spring-cloud-openfeign.version} 的版本为 2.2.5.RELEASE

注意事项: Spring Cloud Alibaba 2.2.3.RELEASE 版本支持的 Spring Boot 版本为 2.3.1.RELEASE ,建议在搭建项目时要保持版本的一致性,Spring Boot 版本过高或过低都可能导致不兼容问题

3 核心代码

3.1 application 配置文件

./cloud-alibaba-server-consumer-feign/src/main/resources/application.yml
## config

## server
server:
  port: 8604

## spring
spring:
  application:
    name: cloud-alibaba-server-consumer-feign
  cloud:
    nacos:
      discovery:
        server-addr: 172.16.140.10:8688

## endpoint
management:
  endpoints:
    web:
      exposure:
        include: "*"

简要配置说明:

spring.application.name: 应用名称,同时也是服务的名称

spring.cloud.nacos.discovery.server-addr: Nacos 服务的地址,包括 ip 和 端口,这里需要保证 Nacos 服务器的端口可访问

3.2 Service 层-服务调用

./cloud-alibaba-server-consumer-feign/src/main/java/com/ljq/demo/springboot/alibaba/server/consumer/feign/service/NacosConsumerService.java
package com.ljq.demo.springboot.alibaba.server.consumer.feign.service;

import com.ljq.demo.springboot.alibaba.server.consumer.feign.common.constant.NacosConst;
import com.ljq.demo.springboot.alibaba.server.consumer.feign.model.param.HelloParam;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @Description: Nacos 服务消费者业务层
 * @Author: junqiang.lu
 * @Date: 2020/12/2
 */
@FeignClient(NacosConst.NACOS_SERVER_PROVIDER_NAME)
public interface NacosConsumerService {

    /**
     * hello
     * @param helloParam
     * @return
     */
    @GetMapping(value = "/api/nacos/hello", produces = {MediaType.APPLICATION_JSON_VALUE})
    ResponseEntity<String> hello(@SpringQueryMap HelloParam helloParam);

    /**
     * 回复
     *
     * @param helloParam
     * @return
     */
    @PostMapping(value = "/api/nacos/replay", produces = {MediaType.APPLICATION_JSON_VALUE})
    ResponseEntity<String> replay(@RequestBody HelloParam helloParam);


}

@FeignClient : Feign 客户端注解,用在接口上,value/name 属性用于指定请求服务的 ID

在接口中的方法上使用 Spring 的 @RequestMapping/@GetMapping/@PostMapping 等注解,指定服务提供者的接口路径和请求方法

3.3 Controller 控制层

./cloud-alibaba-server-consumer-feign/src/main/java/com/ljq/demo/springboot/alibaba/server/consumer/feign/controller/NacosConsumerController.java
package com.ljq.demo.springboot.alibaba.server.consumer.feign.controller;

import com.ljq.demo.springboot.alibaba.server.consumer.feign.model.param.HelloParam;
import com.ljq.demo.springboot.alibaba.server.consumer.feign.service.NacosConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @Description: nacos 服务消费者控制层
 * @Author: junqiang.lu
 * @Date: 2020/12/2
 */
@Slf4j
@RestController
@RequestMapping("/api/nacos/consumer")
public class NacosConsumerController {

    @Autowired
    private NacosConsumerService consumerService;

    @GetMapping(value = "/hello", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<String> hello(HelloParam helloParam) {
        ResponseEntity<String> response = consumerService.hello(helloParam);
        log.info("response: {}", response.getBody());
        return response;
    }

    @PostMapping(value = "/replay", produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<String> replay(@RequestBody HelloParam helloParam) {
        ResponseEntity<String> response = consumerService.replay(helloParam);
        log.info("response: {}", response.getBody());
        return response;
    }


}

3.4 SpringBoot 启动类

./cloud-alibaba-server-consumer-feign/src/main/java/com/ljq/demo/springboot/alibaba/server/consumer/feign/CloudAlibabaServerConsumerFeignApplication.java
package com.ljq.demo.springboot.alibaba.server.consumer.feign;

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

/**
 * @author junqiang.lu
 */
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
public class CloudAlibabaServerConsumerFeignApplication {

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

}

@EnableFeignClients :启用 Feign 的注解

3.5 其他相关代码

常量类

./cloud-alibaba-server-consumer-feign/src/main/java/com/ljq/demo/springboot/alibaba/server/consumer/feign/common/constant/NacosConst.java
package com.ljq.demo.springboot.alibaba.server.consumer.feign.common.constant;

/**
 * @Description: Nacos 相关常量
 * @Author: junqiang.lu
 * @Date: 2020/12/2
 */
public class NacosConst {

    private NacosConst() {
    }

    public static final String NACOS_SERVER_PROVIDER_NAME = "cloud-alibaba-server-provider";
}

请求参数接收类

./cloud-alibaba-server-provider/src/main/java/com/ljq/demo/pringboot/alibaba/server/provider/model/param/HelloParam.java
package com.ljq.demo.pringboot.alibaba.server.provider.model.param;

import lombok.Data;

import java.io.Serializable;

/**
 * @Description: 用户实体类
 * @Author: junqiang.lu
 * @Date: 2020/12/2
 */
@Data
public class HelloParam implements Serializable {

    private static final long serialVersionUID = 2958405318099108563L;

    /**
     * 用户名
     */
    private String name;
}

4 请求测试

依次启动服务提供者项目 cloud-alibaba-server-provider,服务消费者项目 cloud-alibaba-server-consumer-feign

打开 Nacos 控制台,可以看到两个服务

请求服务消费者的接口

4.1 GET 方式请求接口

接口地址与请求参数:

http://127.0.0.1:8604/api/nacos/consumer/hello?name=%E5%BE%B7%E7%8E%9B%E8%A5%BF%E4%BA%9A

请求方式: GET

返回结果:

Hello,德玛西亚

服务消费者日志:

2020-12-15 15:30:20.457  INFO 76432 --- [nio-8604-exec-1] .l.d.s.a.s.c.f.c.NacosConsumerController : response: Hello,德玛西亚

服务提供者日志:

2020-12-15 15:30:20.353  INFO 76411 --- [nio-8600-exec-1] c.l.d.p.a.s.p.c.NacosProviderController  : serverPort: 8600
2020-12-15 15:30:20.353  INFO 76411 --- [nio-8600-exec-1] c.l.d.p.a.s.p.c.NacosProviderController  : result: Hello,德玛西亚

4.2 POST 方式请求接口

接口地址:

http://127.0.0.1:8604/api/nacos/consumer/replay

请求参数:

{
    "name": "卢本伟"
}

请求方式: POST

返回结果:

Hi,卢本伟,I'm fine,Thank you.

服务消费者日志:

2020-12-15 15:31:26.906  INFO 76432 --- [nio-8604-exec-3] .l.d.s.a.s.c.f.c.NacosConsumerController : response: Hi,卢本伟,I'm fine,Thank you.

服务提供者日志:

2020-12-15 15:31:26.904  INFO 76411 --- [nio-8600-exec-3] c.l.d.p.a.s.p.c.NacosProviderController  : result: Hi,卢本伟,I'm fine,Thank you.

至此,一个基于 Spring Cloud Alibaba 2.2 使用 Feign 的服务消费者框架已经搭建完成

5 推荐参考资料

Spring Cloud Alibaba系列教程 - Spring Cloud Alibaba 创建服务消费者(Feign)

6 本次提交记录

commit f4271a5c834e0975b14ba3bc06dc59747f927400 (HEAD -> dev, origin/master, origin/dev, origin/HEAD, master)
Author: ljq <flying9001@gmail.com>
Date:   Sun Dec 13 12:01:36 2020 +0800

    代码-新增基于 Spring boot 2.3 搭建 Spring Cloud Alibaba 2.2 微服务框架

版本回退命令

git reset --soft f4271a5c834e0975b14ba3bc06dc59747f927400