SpringBoot集成OpenFeign,实现服务间的相互调用

SpringBoot集成OpenFeign,实现服务间的相互调用

文章目录

  • SpringBoot集成OpenFeign,实现服务间的相互调用
    • 一、实验准备与目标
    • 二、添加依赖
    • 三、写调用接口
    • 四、写controller层
    • 五、启动类注解
    • 六、结果

一、实验准备与目标

有业务模块business和跑批模块batch

business模块中设有test接口,内容如下:

@RestController
public class TestController {

    @GetMapping("/test")
    public String test(){
        return "test business";
    }

}

目标是在batch模块中调用business模块的test接口,以此模拟微服务环境下,不同服务之间相互调用的情况。

二、添加依赖

在调用模块中添加依赖,即在batch模块添加:


        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-loadbalancerartifactId>
        dependency>

三、写调用接口

BusinessFeign.java:

 @FeignClient(name = "business", url = "http://127.0.0.1:8002")
public interface BusinessFeign {

    @GetMapping("/business/test")
    String hello();

}

注意要在business模块配置中申明该模块是business,这样微服务之间才能互相认识。

spring.application.name=business

四、写controller层

@RestController
public class TestController {

    private static final Logger LOG = LoggerFactory.getLogger(TestController.class);

    @Resource
    BusinessFeign businessFeign;

    @GetMapping("/test")
    public String hello() {
        String businessHello = businessFeign.hello();
        LOG.info(businessHello);
        return "Hello World! Batch! " + businessHello;
    }

}

五、启动类注解

batch模块启动类上添加注解:@EnableFeignClients("com.mystudy.train.batch.feign")
申明开启feign代理,告知SpringBoot哪里是feign代理。

六、结果

business模块中日志打印:
SpringBoot集成OpenFeign,实现服务间的相互调用_第1张图片
batch模块中日志打印:
SpringBoot集成OpenFeign,实现服务间的相互调用_第2张图片
由此可见,成功在batch模块中调用business模块的test接口,并返回数据结果。

你可能感兴趣的:(我的小成就,spring,boot,后端,java,springcloud,微服务)