定制设计在实际开发中,定制设计需要服务之间的调用,定制设计如何实现两个服务
1,定制设计先看下项目架构
我们参考ruoyi--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);}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
其中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 */@Componentpublic 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()); } }; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
配置文件,我们把ruoyi-api-system中的复制改下就行
注意这个地方路径别写错了,否则可能会找不到bean
4,
我们现在写服务提供方,注意路径、方法名别写错了,这里我们随便在service里面返回点什么文字,
5,我们在写服务消费方
在system中随便找个controller下面调用下我们ruoyi-api-tsmk中的方法
这里需要引入包,
6,开始测试
把认证、网关、系统、tsmk服务启动
使用postman测试
测试结果:服务system成功调用tsmk的接口