欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Kite的学习历程SpringCloud之Hystrix服务降级

程序员文章站 2022-06-06 14:34:03
...

Kite学习历程的第二十三天

Hystrix服务降级

1. 创建Hystrix服务器端cloud-provider-hystrix-payment-8001

1.1 修改pom.xml文件

记得引入:spring-cloud-starter-netflix-hystrix依赖

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>demo01cloud</artifactId>
        <groupId>cn.kitey.spring</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloud-provider-hystrix-payment-8001</artifactId>


    <dependencies>
        <!--引入hystrix-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!--引入自己创建的entities包-->
        <dependency>
            <groupId>cn.kitey.spring</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--监控-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId><!-- -->
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

1.2 创建application.yml配置文件

server:
  port: 8001

spring:
  application:
    name: cloud-provider-hystrix-payment

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      #就在一个注册中心进行注册
      defaultZone: http://eureka7001.com:7001/eureka

1. 3 创建主启动类

注意添加注解:
@EnableCircuitBreaker: 用于服务降级


package cn.kitey.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
public class PaymentHystrixMain8001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentHystrixMain8001.class, args);
    }
}

1.4 创建service 业务层

三个方法:

  1. 正常的方法
  2. 设置了超时,并使用@HystrixCommand,设置了服务降级
  3. 被方法二指定的的服务降级方法
package cn.kitey.springcloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class PaymentService {
    /**
     * 正常访问的操作
     * @param id
     * @return
     */
    public String paymentInfo_OK(Long id){
        return "线程池:  " + Thread.currentThread().getName() +
                "   paymentInfo_OK.id: " + id;
    }

    /**
     * 超时
     * @param id
     * @return
     */
    @HystrixCommand(
            //启用服务降级
            fallbackMethod = "paymentInfo_TimeOutHandler",
            //设置该方法的超时时间限制
            commandProperties = {@HystrixProperty(
                    name = "execution.isolation.thread.timeoutInMilliseconds",
                    value = "3000")}
    )
    public String paymentInfo_TimeOut(Long id){
        int timeNumber = 2000;
        try {
            //程序休眠3秒中
            TimeUnit.MILLISECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:  " + Thread.currentThread().getName() +
                "   paymentInfo_TimeOut.id: " + id + "   程序耗时"+ timeNumber+"毫秒钟";
    }

    /**
     * 服务降级执行方法
     * @param id
     * @return
     */
    public String paymentInfo_TimeOutHandler(Long id){
        return "线程池:  " + Thread.currentThread().getName() +
                "   paymentInfo_OK.id: " + id + "\t" + "服务降级后的执行方法";
    }

}


1.5 controller 控制类创建

提供访问地址,调用service方法

package cn.kitey.springcloud.contrller;

import cn.kitey.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Value("@{server.port}")
    private String serverPort;

    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentInfo_OK(@PathVariable("id") Long id){
        String info_ok = paymentService.paymentInfo_OK(id);
        log.info("------result:" + info_ok);
        return info_ok;
    }

   @GetMapping("/payment/hystrix/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Long id){
        String info_ok = paymentService.paymentInfo_TimeOut(id);
        log.info("------result:" + info_ok);
        return info_ok;
    }

}


2 进行测试

  1. 首先访问正常的:

http://localhost:8001/payment/hystrix/ok/1Kite的学习历程SpringCloud之Hystrix服务降级
2 首先设置
服务器等待时间3000毫秒大于方法的延迟时间2000毫秒进行访问
Kite的学习历程SpringCloud之Hystrix服务降级
访问地址:
http://localhost:8001/payment/hystrix/timeout/1
Kite的学习历程SpringCloud之Hystrix服务降级
3 设置方法延迟时间为5000 毫秒大于3000 毫秒
Kite的学习历程SpringCloud之Hystrix服务降级
访问地址:
http://localhost:8001/payment/hystrix/timeout/1
Kite的学习历程SpringCloud之Hystrix服务降级
这时就会执行服务降级设置的方法,避免程序出现错误页面