zoukankan      html  css  js  c++  java
  • 5.Hystrix-服务降级

    所谓降级,就是当某个服务出现异常之后,服务器将不再被调用,此时服务端可以自己准备一个本地的fallback回调,返回一个缺省值。
    这样做,虽然服务水平下降,但好歹可用,比直接挂掉要强,当然这也要看适合的业务场景。

    启动类:

    package com.wangfajun;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.SpringCloudApplication;
    import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    
    //@SpringBootApplication
    //@EnableDiscoveryClient
    //@EnableCircuitBreaker //开启断路器
    @SpringCloudApplication
    public class FajunClientTestApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(FajunClientTestApplication.class, args);
        }
    }

    服务端代码demo(客户端请求服务端serverMethod方法时,如果服务端宕机或是serverMethod抛出异常,则将调用defaultFallback方法):

    package com.odao.client.controller;
    
    import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
    import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
    import org.springframework.web.bind.annotation.*;
    
    @RestController
    @DefaultProperties(defaultFallback = "defaultFallback")
    public class FeignClientTestController {
    
        @HystrixCommand
        @GetMapping(value = "serverMethod")
        public String serverMethod() {
        /*throw new RuntimeException("异常了");*/
        return null; 
      }

      public String defaultFallback() {
        return "太拥挤了";
      }

    pom:

    <!--hystrix-->
     <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-hystrix</artifactId>
    </dependency>           
  • 相关阅读:
    Java读取resource文件/路径的几种方式
    log4j:WARN Please initialize the log4j system properly解决办法
    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    log4j.properties配置详解与实例-全部测试通过[转]
    testNG中dataprovider使用的两种方式
    远程仓库获取最新代码合并到本地分支
    git 冲突解决办法
    【转】JsonPath教程
    selenium及webdriver的原理【转】
    [转]Redis 数据结构简介
  • 原文地址:https://www.cnblogs.com/wangfajun/p/9294961.html
Copyright © 2011-2022 走看看