乐趣区

关于java:Hystrix服务保护框架-服务降级Fallback

前言

后面咱们应用 @HystrixCommand 注解来做服务熔断降级。这种形式存在很大的弊病,代码冗余,并且是不论是否降级都当时开启了新线程,而应用 fallback 的形式则不调用 feign 办法前都是在之前的主线程中,只有超时了,才会开新线程来解决,这样性能上更好。

代码革新

Hystrix 应用类形式

//Hystrix 第二种形式,应用类形式
@RequestMapping("/getUserInfoByMemberHystrix2")
public BaseResponse getUserInfoByMemberHystrix2() {System.out.println("getUserInfoByMemberHystrix--> 线程池名称:" + Thread.currentThread().getName());
 return memberServiceFeign.getUserInfo();}

MemberServiceFallback

package com.baba.api.fallback;
import com.baba.api.entity.UserEntity;
import com.baba.api.feign.MemberServiceFeign;
import com.baba.wlb.base.BaseApiService;
import com.baba.wlb.base.BaseResponse;
import org.springframework.stereotype.Component;
/**
 * @Author wulongbo
 * @Date 2021/1/28 10:13
 * @Version 1.0
 */@Component
public class MemberServiceFallback extends BaseApiService implements MemberServiceFeign {
    @Override
 public UserEntity getMember(String name) {return null;}
    // 服务降级敌对提醒
 @Override
 public BaseResponse getUserInfo() {return setResultError("以类的形式写服务降级,服务器忙碌,请稍后重试!");
 }
}

MemberServiceFeign

@FeignClient(name = "app-member") 改为 @FeignClient(value = "app-member",fallback = MemberServiceFallback.class)

package com.baba.api.feign;
import com.baba.api.fallback.MemberServiceFallback;
import com.baba.api.service.IMemberService;
import org.springframework.cloud.openfeign.FeignClient;
/**
 * @Author wulongbo
 * @Date 2021/1/22 14:12
 * @Version 1.0
 *///@FeignClient(name = "app-member")
@FeignClient(value = "app-member",fallback = MemberServiceFallback.class)
public interface MemberServiceFeign extends IMemberService{}

这样就实现了类的形式调用 Fallback。

退出移动版