SpringCloud Feign+Hystrix ,一直是走fallback,问题解决

问题描述:

UserClient

@FeignClient(value = "userservice", fallback = UserClientFallback.class)
public interface UserClient {

    @GetMapping("user/{id}")
    User queryById(@PathVariable("id") Long id);

}

UserClientFallback

@Component
public class UserClientFallback implements UserClient {
    @Override
    public User queryById(Long id) {
        User user = new User();
        user.setName("未知用户");
        return user;
    }
}

controller

@RestController
@RequestMapping("consumer")
@DefaultProperties(defaultFallback = "queryUserByIdFallback")
public class ConsumerController {

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryUserById(@PathVariable("id") Long id) {
        return userClient.queryById(id);
    }
    
    public User queryUserByIdFallback() {
        User user = new User();
        user.setName("用户信息查询出现异常!");
        return user;
    }

服务提供者是可用的,消费者客户端一直走fallback方法

问题原因:

如果执行的方法导致Hystrix超时也会去执行fallback方法,这样也就不会去执行业务代码。

Hystrix有个默认的超时时间,默认是1000ms(1秒),源码如下:

private static final Integer default_executionTimeoutInMilliseconds = 1000; // default => executionTimeoutInMilliseconds: 1000 = 1 second

问题解决:

我们设置Hystrix的超时时间更久,要超过Ribbon等的超时时间(此配置在IDEA里是没有信息提示):
SpringCloud Feign+Hystrix ,一直是走fallback,问题解决_第1张图片

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 6000 # 设置hystrix的超时时间为6000ms

本人yml配置:

server:
  port: 8080
spring:
  application:
    name: userconsumer
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:8088/eureka
  instance:
    prefer-ip-address: true # 当其它服务获取地址时提供ip而不是hostname
    ip-address: 127.0.0.1 # 指定自己的ip信息,不指定的话会自己寻找
ribbon:
  NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule # 默认为;轮询,这里改为随机
  ConnectTimeout: 5000 # 连接超时时间(ms)
  ReadTimeout: 5000 # 通信超时时间(ms)
feign:
  hystrix:
    enabled: true # 开启Feign的熔断功能
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 6000 # 设置hystrix的超时时间为6000ms

你可能感兴趣的:(Java,SpringCloud)