码上敲享录 > SpringCloud实战教程 > Springcloud服务提供者整合断路器Hystrix实现发生异常时友好提示

Springcloud服务提供者整合断路器Hystrix实现发生异常时友好提示

上一章章节目录下一章 2020-06-23已有1074人阅读 评论(0)

各个章节可能有关联关系,查找《SpringCloud实战教程》其他章节请参考:

http://www.yayihouse.com/yayishuwu/book/79



7. Springcloud服务提供者整合断路器Hystrix实现发生异常时友好提示

(1) 在前面第二章《idea创建springcloud服务提供者工程euraka-client》基础上演示,在pom.xml文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
     <groupId>com.wlg.springcloud</groupId>
     <artifactId>springcloud</artifactId>
     <version>0.0.1-SNAPSHOT</version>
  </parent>
  <groupId>com.wlg.springcloud</groupId>
  <artifactId>eureka-client</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>eureka-client</name>
  <description>Demo project for Spring Boot</description>
  <dependencies>
     <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
     </dependency>
     <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
     </dependency>
  </dependencies>
</project>

(2) Springboot启动类代码:

@SpringBootApplication
@EnableDiscoveryClient
@EnableHystrix
public class EurekaClientApplication {
  public static void main(String[] args) {
     SpringApplication.run(EurekaClientApplication.class, args);
  }
}

(3) 核心方法:

当用户访问sayHello传参数txt0时抛出异常,那么就会执行fallback返回信息给用户

@Controller
public class FeignServerController {
    @RequestMapping("/hello")
    @ResponseBody
    @HystrixCommand(fallbackMethod = "fallback")
   public  String sayHello(@RequestParam("txt") String txt) throws Exception {
        if("0".equals(txt)){
           throw new Exception();
        }
        return  "收到你传过来的参数为:"+txt;
    }

   public String fallback(String txt){
        return  "收到你传过来的参数为:"+txt+",但系统正在维护中。。。";
    }

}

(4) 演示:

启动前面章节创建的服务发现及注册中心eurekaServer和启动这个eureka-client

浏览器访问:http://localhost:9902/hello?txt=1

结果:收到你传过来的参数为:1

浏览器访问:http://localhost:9902/hello?txt=0

结果:收到你传过来的参数为:0,但系统正在维护中。。。

这就说明了hystrix捕捉并处理了异常,最后返回自己设置好的信息给用户,体验就会好很多。


向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交