Ribbon+Hystrix+FeignClient 实现跨模块+跨服务远程调用

一.引入 Ribbon+Hystrix依赖 +feign依赖

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        <version>2.2.5.RELEASE</version>
    </dependency>

    <!--ribbon负载均衡-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        <version>2.2.5.RELEASE</version>
    </dependency>

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

注意: Ribbon+Hystrix 依赖尽量一致 否则会报异常 自己可以试试嘻嘻!!


二.yml配置Ribbon+Hystrix

# feign远程配置
# 这个gd-ae是用户模块 多模块后面打点添加
gd-ae:
  ribbon:
    ## 服务提供者的地址,不是服务注册中心的地址
    listOfServers: http://localhost:8088

# 开启熔断
feign:
  #Hystrix超时时间设置 原因 feign第一次调用需要懒加载并且装在bean 所以第一次比较慢
   hystrix:
     enabled: true
   client:
     config:
      default:
        connectTimeout: 5000 #连接超时时间2秒
        readTimeout: 5000 #读超时时间2秒
        
hystrix:
  command:
    default: #也可以针对多个服务
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 4000 # 设置hystrix的超时时间为4000ms

注意: 1.一定要设置熔断时间 原因: feign第一次调用需要懒加载并且装在bean 所以第一次比较慢 如果不设置可能会被熔断调

​ 2.也可以设置ribbon重复调用时间 这里没有设置


三.启动类上添加注解

@EnableFeignClients(basePackages = {"com.guodian.api"}) //basePackages = 指定的api远程模块所在包
@EnableHystrix

四.实现跨模块调用

请添加图片描述

调用方client 模块gd-web

如下图

请添加图片描述

1.client(gd-web模块)代码

@Api(tags = "调用方模块")
@Slf4j
@RestController
@RequestMapping("/web")
public class UserController extends BaseController {
	
    //注入远程服务中转站Ribbon
    @Resource
    private RemoteUserService remoteUserService;


    @GetMapping("/getUser")
    public String getUser(Long userId){
        return remoteUserService.remoteGetUser(userId).checkAndGt();
    }

} 

2.feign(gd-web远程模块)代码


/**
 * @author: wfs
 * @date: 2022/3/15 15:30
 * @version: 1.0
 */
@FeignClient(contextId = "remoteUserService",value = FeignServiceConstants.GD_AE,fallbackFactory = RemoteUserFactory.class )
public interface RemoteUserService {

    /**
     * 获取用户信息
     * @param userId 用户
     * @return 客户
     */
    @GetMapping("/user/login") //这里地址必须要和 serve服务方地址相同 否则找不到 gd-ae用户模块具体的接口地址
    R<String> remoteGetUser(@RequestParam("userId") Long userId);
    
}

3.@FeignClient标签的常用属性如下:

内容含义
value当前服务名
name指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现
urlurl一般用于调试,可以手动指定@FeignClient调用的地址
decode404:当发生http 404错误时,如果该字段位true,会调用decoder进行解码,否则抛出FeignException
configurationFeign配置类,可以自定义Feign的Encoder、Decoder、LogLevel、Contract
fallback定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口
fallbackFactory工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码
path定义当前FeignClient的统一前缀

4.熔断代码

/**
 * @author: wfs
 * @date: 2022/3/15 16:22
 * @version: 1.0
 */
public class RemoteUserFactory implements FallbackFactory<RemoteUserService> {
    //日志打印
    private static final Logger log = LoggerFactory.getLogger(RemoteUserFactory.class);

    @Override
    public RemoteUserService create(Throwable throwable) {
        log.info("远程WebSocket服务调用失败!{}", throwable.getMessage());

        
        return new RemoteUserService() {
            @Override //熔断报错内容
            public R<String> remoteGetUser(Long userId) {
                return R.fail("远程调用登录用户失败!!");
            }
        };
    }
}

注意: 这里一定要指定路径 熔断路径 在resources下 创建 META-INF目录 再创建spring.factories文件 指定熔断类路径 否则会报异常 自己可以试试!!!

如下 api模块架构图及文件目录 可以参考

请添加图片描述

spring.factories 内容

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.guodian.api.factory.RemoteUserFactory,\
com.guodian.api.factory.RemoteGetUserFactory 

5.server服务方代码 提供用户信息

@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class AeUserController extends BaseController {

    
    @GetMapping("/login")
    public R<String> user(Long userId){
        if (userId.equals(3L)){
            return R.ok("获取用户成功!!");
        }
        return R.fail("获取用户失败!!");
    }
}

五.测试代码

我们调用gd-web模块中 http://*******/web/getUser 接口 传值userId 为3 查看结果

请添加图片描述
OK搞定

六.跨服务调用

这里是我写的 跨服务调用—远程调用接口 点击这里!!
跨服务调用—远程调用接口

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只可爱的委屈翁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值