@HystrixCommand无法在内部方法调用上使用

时间:2019-06-07 07:30:42

标签: spring-boot hystrix

我有方法@Service注释的类,该类调用远程服务。当我向该方法添加@HystrixCommand时,它的工作正常。 但是当该远程服务调用独立于新方法并将@HystrixCommand添加到第二种方法时,Hystrix停止工作。第二种方法也是同一类的公共方法。

  1. 这是错误还是设计错误?
  2. 如何解决此问题?

注意: 在工作示例中,我添加了HttpHeaders作为参数,因为在hystrix命令

中无法访问SecurityContextHolder.getContext()

//此功能正常

 @HystrixCommand(fallbackMethod = "fetchEmployeesBack")
    public Employee fetchEmployees(Employee employee,HttpHeaders httpHeaders) {
        Optional<Employee> optionalEmployee = employeeRepository.findById(employee.getId());
        if (optionalEmployee.isPresent()) {
            //fetch project allocation
            ResponseEntity<Allocation[]> responseEntity;
            HttpEntity<String> entity = new HttpEntity<>("", httpHeaders);
            responseEntity =
                    restTemplate.exchange("http://allocation-service/rest/allocations/".
                            concat(employee.getId().toString()), HttpMethod.GET, entity,Allocation[].class);
            Employee employee1 = optionalEmployee.get();
            System.out.println(responseEntity.getBody().toString());
            employee1.setAllocations(responseEntity.getBody());
            return employee1;
        } else {
            return null;
        }
    }

//这不起作用

    public Employee fetchEmployees(Employee employee) {
        Optional<Employee> optionalEmployee = employeeRepository.findById(employee.getId());
        if (optionalEmployee.isPresent()) {

            Employee employee1 = optionalEmployee.get();
            Allocation[] allocations = fetchEmployeesAllocation(optionalEmployee.get());
            employee1.setAllocations(allocations);
            return employee1;
        } else {
            return null;
        }
    }

    @HystrixCommand(fallbackMethod = "fetchEmployeesAllocationFallback")
    public Allocation[] fetchEmployeesAllocation(Employee employee) {
        //fetch project allocation
        HttpHeaders httpHeaders = new HttpHeaders();
        //extract token from context
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)
                SecurityContextHolder.getContext().getAuthentication().getDetails();
        httpHeaders.add("Authorization", "bearer ".concat(details.getTokenValue()));
        //
        ResponseEntity<Allocation[]> responseEntity;
        HttpEntity<String> entity = new HttpEntity<>("", httpHeaders);

        responseEntity =
                restTemplate.exchange("http://allocation-service/rest/allocations/".
                        concat(employee.getId().toString()), HttpMethod.GET, entity, Allocation[].class);
        return responseEntity.getBody();
    }

在此无效示例中,它给出了功能区异常,表明没有运行分配服务中的实例。它不能识别为hystrix命令

0 个答案:

没有答案