若依微服务框架两个服务之间调用-参考ruoyi-api-system

在实际开发中,需要服务之间的调用,若依框架如何实现两个服务
1,先看下项目架构

在这里插入图片描述我们参考ruoyi-api-sysytem来写,其中我们服务提供写在ruoyi-tsmk(可以参考往期,如何新增一个业务模块),消费写在ruoyi-system(简单测试下)

2,若依采用的是FeignClient
我们先来看看FeignClient注解可能涉及到的参数
在这里插入图片描述value-服务提供方的服务名称,在这里面我们的服务提供是ruoyi-tsmk,因此
在这里插入图片描述2,我们在ruoyi-api下面新建一个模块
在这里插入图片描述在这里插入图片描述3,新建完毕后,我们建一个包,新建一个接口
在这里插入图片描述RemoteStudentService类代码参考如下:

package com.ruoyi.tsmk.api;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.constant.ServiceNameConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.tsmk.api.factory.RemoteStudentFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.*;

/**
 * 用户服务
 * 
 * @author ruoyi
 */
@FeignClient(contextId = "remoteStudentService", value = ServiceNameConstants.TSMK_SERVICE, fallbackFactory = RemoteStudentFallbackFactory.class)
public interface RemoteStudentService
{
    /**
     * 通过用户名查询用户信息
     *
     * @return 结果
     */
    @GetMapping("/student/get/{id}")
    public R<String> getStudent(@PathVariable("id") Long id);


}

其中contextId 别和其他的重复,同一服务下唯一性

@GetMapping(“/student/get/{id}”)
public R getStudent(@PathVariable(“id”) Long id);

这个路径与我们等会在消费方需要保持一致,其中R是若依用来统一处理的对象。

RemoteStudentFallbackFactory 类是回馈用的,

package com.ruoyi.tsmk.api.factory;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.tsmk.api.RemoteStudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

/**
 * 用户服务降级处理
 * 
 * @author ruoyi
 */
@Component
public class RemoteStudentFallbackFactory implements FallbackFactory<RemoteStudentService>
{
    private static final Logger log = LoggerFactory.getLogger(RemoteStudentFallbackFactory.class);

    @Override
    public RemoteStudentService create(Throwable throwable)
    {
        log.error("用户服务调用失败:{}", throwable.getMessage());
        return new RemoteStudentService()
        {
            @Override
            public R<String> getStudent(Long id)
            {
                return R.fail("获取用户失败:" + throwable.getMessage());
            }


        };
    }
}

配置文件,我们把ruoyi-api-system中的复制改下就行
在这里插入图片描述在这里插入图片描述注意这个地方路径别写错了,否则可能会找不到bean
在这里插入图片描述4,
我们现在写服务提供方,注意路径、方法名别写错了,这里我们随便在service里面返回点什么文字,
在这里插入图片描述
在这里插入图片描述5,我们在写服务消费方
在system中随便找个controller下面调用下我们ruoyi-api-tsmk中的方法
在这里插入图片描述这里需要引入包,
在这里插入图片描述6,开始测试
把认证、网关、系统、tsmk服务启动
使用postman测试

在这里插入图片描述
在这里插入图片描述
测试结果:服务system成功调用tsmk的接口
在这里插入图片描述

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>