zl程序教程

您现在的位置是:首页 >  Java

当前栏目

Hystrix的服务降级处理基本使用

2023-02-18 16:35:52 时间

导包

SpringCloud和SpringBoot基本依赖这里就不导入了,相信你也导入了

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

引导类上开启Hystrix

在引导类上加上 @EnableHystrix或者 @EnableCircuitBreaker再在或者 @SpringCloudApplication

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

@SpringBootApplication
//@SpringCloudApplication
@EnableDiscoveryClient
@EnableHystrix //开启Hystrix
public class UserConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserConsumerApplication.class,args);
    }

    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
}

在Controller层中添加方法降级方法

案例:

public String findByIdFallback(Long id){
   return "服务器忙,请稍后重试....";
 }

在需要降级的方法添加注解进行降级

下方法上添加 @HystrixCommand(fallbackMethod="方法名称") 案例:

@GetMapping("/{id}")
@HystrixCommand(fallbackMethod="findByIdFallback")  //只针对此方法的降级
public  String findById(@PathVariable("id") Long id){
    String user = restTemplate.getForObject("http://user-service/user/"+id, String.class);
    return user;
}

全局降级

每一个方法都需要降级的话,上面的那种就麻烦了,所有Hystrix有全局降级

写一个统一的降级方法

public String allMethodFallBack(){
   return " 服务器疯狂吃饭中......";
 }

在类上写添加一个注解 @DefaultProperties(defaultFallback="全局降级方法") 在需要使用降级的方法上添加 @HystrixCommand ,不加注解的不走降级方法 案例:

import com.leyou.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;

@RestController
@RequestMapping("/con")
@DefaultProperties(defaultFallback = "allMethodFallBack")
public class UserConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/{id}")
    @HystrixCommand//降级处理
    public String findById(@PathVariable("id") Long id){
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        ServiceInstance serviceInstance = instances.get(0);
        //User user = restTemplate.getForObject("http://localhost:8081/user/"+id, User.class);
        String user = restTemplate.getForObject(serviceInstance.getUri()+"/user/"+id, String .class);
        return user;
    }

    public String allMethodFallBack(){
        return "服务器干饭中.....";
    }
}

Hystix的默认超时时长为1秒,我们可以通过配置修改这个值,直接复制如下即可,这个配置没有提示的

hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 2500 #单位毫秒