跨服务openfeign远程调用

不同数据库之间是不能关联查询,这时候需要用到远程调用openfeign来获取其他数据库的数据

1.导入依赖

<!--openFeign远程调用-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>3.1.3</version>
</dependency>

两个模块(调用和被调用的模块)都需要导入openfeign的依赖

2.按照正常流程编写代码(controller层,service层,dao层,此次略过)

/**
     *根据用户获取id
     */
    @GetMapping("getUserById/{userId}")
    public User getUserById(@PathVariable int userId){
        return userService.getUserById(userId);
    }
User getUserById(int userId);
@Override
    public User getUserById(int userId) {
        return userMapper.selectById(userId);
    }

3.在被调用模块的启动类上加上@EnableFeignClients注解

@SpringBootApplication
@MapperScan("com.lyy.user.mapper")
@EnableFeignClients
public class UserApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }
}

调用方的启动类上也加上注解

@SpringBootApplication
@MapperScan("com.lyy.comment.mapper")
@RefreshScope
@EnableFeignClients(basePackages = "com.lyy.common.client")
public class CommentApplication {
    public static void main(String[] args) {
        SpringApplication.run(CommentApplication.class, args);
    }
}

basePackages = "com.lyy.common.client"指向下面编写的远程调用接口

4.编写远程调用接口

我这里是在common公共类中编写,也可以在调用模块的中创建

@FeignClient("pp-service-user")
public interface UserClient {

    /**
     *根据用户获取id
     */
    @GetMapping("user/getUserById/{userId}")
    User getUserById(@PathVariable int userId);
}

注意点:a:需要加上@FeignClient("pp-service-user")

                这个名字应该和applition.yml中的application-name相同

                b:方法要和userController中的方法一致,下图可以看到区别

5.直接在调用模块注入UserClient 就可以使用方法了!!!

附加:

我从comment数据库获取到了评论的列表,但是需要在dto中加入user数据库中才有的头像,所有就用到了openfeign进行远程调用,现在只需要遍历list,给list中的每一个user加上头像的值就可以了!!!!!加油

  • 11
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值