Spring Cloud Alibaba-整合Feign调用接口

564 阅读1分钟

echo编辑整理,欢迎转载,转载请声明文章来源。欢迎添加echo微信(微信号:t2421499075) 交流学习。


该文章是系列文章,如果不熟悉西SpringCloud的,还是需要先看看前面的文章。

当我们通过前面的学习,完成了服务注册与发现之后,我们发现我们的通信方式稍微有点复杂,所以这里单独讲讲Feign的整合。这里基于《Spring Cloud Alibaba-接入Nacos注册中心了解服务注册与发现》文章中的项目

添加相关的依赖

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

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-dependencies</artifactId>
	<version>Hoxton.SR9</version>
	<type>pom</type>
	<scope>import</scope>
</dependency>

调整consumer项目的接口调用方式

  • 第一步:在启动类上面添加如下注解
@EnableFeignClients

添加Feign接口类

该接口类对应的接口,就是我们服务提供者里面的方法

@FeignClient("spring-cloud-nacos-server")
public interface TestClient {

    @GetMapping("/test")
    public String test();

}

改写从consumer中test的调用方式

@RestController
public class Test {

    @Autowired
    private TestClient testClient;

    @GetMapping("/test")
    public String test() {
        String result = testClient.test();
        return "消费者端调用提供者端返回消息:" + result;
    }

}

启动服务,使用工具调用,结果如下

在这里插入图片描述

  • 上一篇:Spring Cloud Alibaba-接入Nacos注册中心了解服务注册与发现
  • 下一篇:Spring Cloud Alibaba-使用nacos做注册中心