SpringCloudAlibaba整合openfeign

本文介绍了如何在微服务架构下利用OpenFeign进行模块间的远程调用。首先,通过创建两个业务模块来演示场景。接着,引入Nacos作为服务注册中心和OpenFeign的相关依赖。在调用方启动类上启用FeignClients注解,并在被调用方编写REST控制器。最后,在调用方定义FeignClient接口并实现远程调用。测试验证了调用的正确性。
摘要由CSDN通过智能技术生成

介绍

微服务架构下,业务的拆分导致我们无法调用其他模块的方法,使用openFeign可以帮助我们解决这一问题

一.建立项目

建立项目之后,我们需要创建两个业务模块

二.引入依赖

使用openfeign必须要和服务注册中心的组件一起使用,这里我们使用nacos来作为我们的服务注册中心

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

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

三.启动类加注解

在调用方的启动类的类名上面加如下注解

import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients

四.编写被调用方的代码

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @RequestMapping("test")
    public void test(){
        System.out.println(1);
    }
}

五.编写调用方的代码

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

@Service//此处service必加
@FeignClient("B")//此处B是B模块的名称
public interface TestService {
    @RequestMapping("test")
    void test();
}
import com.example.a.client.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    private TestService testService;

    @RequestMapping("test")
    public void test(){
        testService.test();
    }

}

然后测试即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值