第十五章 Spring cloud Hystrix支持撤退

一个默认的代码路径,它在打开或出现错误时执行。为一个给定的@ feignclient设置回退属性,将fallback属性设置为实现回退的类名。

您还需要将实现声明为Spring bean

项目结构如下:


OrderController

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.User;
import com.example.demo.feign.UserFeignClient;

//声明式服务
@RestController
public class OrderController {
		
	  @Autowired
	  private UserFeignClient userFeignClient;

	  @GetMapping("/order/{id}")
	  public User findById(@PathVariable Long id) {
	    return this.userFeignClient.findById(id);
	  }

}

User

package com.example.demo.entity;

import java.math.BigDecimal;

public class User {
  private Long id;

  private String username;

  private String name;

  private Short age;

  private BigDecimal balance;

  public Long getId() {
    return this.id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getUsername() {
    return this.username;
  }

  public void setUsername(String username) {
    this.username = username;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Short getAge() {
    return this.age;
  }

  public void setAge(Short age) {
    this.age = age;
  }

  public BigDecimal getBalance() {
    return this.balance;
  }

  public void setBalance(BigDecimal balance) {
    this.balance = balance;
  }

}

UserFeignClient

package com.example.demo.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.example.demo.entity.User;

声明式服务
/**
 * Feign+Hystrix熔断机制,降级
 * @author
 *
 */
@FeignClient(name="spring-cloud-user",fallback=UserHystrixFeignFallBack.class) // 调用哪个服务的名称
public interface UserFeignClient {

	@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
	public User findById(@PathVariable("id") Long id); // 1. @GetMapping不支持 2.
														// @PathVariable得设置value
}

UserHystrixFeignFallBack

package com.example.demo.feign;

import org.springframework.stereotype.Component;

import com.example.demo.entity.User;

@Component
public class UserHystrixFeignFallBack implements UserFeignClient {

	@Override
	public User findById(Long id) {
		return null;
	}

}

SpringCloudOrderApplication

package com.example.demo;

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;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

/**
 * 声明式服务
 *
 */

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients//表示为Fegin客户端
@EnableCircuitBreaker
public class SpringCloudOrderApplication {
	
	public static void main(String[] args) {
		SpringApplication.run(SpringCloudOrderApplication.class, args);
	}
}

application.yml配置

spring:
  application:
    name: spring-cloud-order_feign-hystrix    #微服务的名称
server:
  port: 7909  #微服务端口号
eureka:
  client:
    healthcheck: 
      enabled: true   # 开启健康检查
    serviceUrl:
      defaultZone: http://user:123456@localhost:8761/eureka   #服务eureka的URL地址
  instance:
    prefer-ip-address: true
# 解决第一次请求报超时异常的方案:
hystrix: 
  command: 
    default: 
      execution: 
        isolation: 
          thread: 
            timeoutInMilliseconds: 5000
# 或者:
# hystrix.command.default.execution.timeout.enabled: false
# 或者:

# 超时的issue:https://github.com/spring-cloud/spring-cloud-netflix/issues/768
# 超时的解决方案: http://stackoverflow.com/questions/27375557/hystrix-command-fails-with-timed-out-and-no-fallback-available
# hystrix配置: https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.thread.timeoutInMilliseconds

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example.demo</groupId>
	<artifactId>spring-cloud-order_feign-hystrix</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<name>spring-cloud-order_feign-hystrix</name>
	<description>spring-cloud-order_feign-hystrix</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.1.RELEASE</version>
	</parent>

	<properties>
		<!-- 文件拷贝时的编码 -->  
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		  <!-- 编译时的编码 -->  
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>  
        <!-- jdk版本 -->  
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<!-- 注册中心 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
		<!-- 这个库让我们可以访问应用的很多信息,包括:/env、/info、/metrics、/health等 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<!-- 添加声明式feign依赖 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-feign</artifactId>
		</dependency>
		
		<!-- 用于热部署 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
		</dependency>		
		<!-- 添加hystrix依赖 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-hystrix</artifactId>
		</dependency>	
	</dependencies>
	<dependencyManagement>
		<dependencies>
		<!-- 版本依赖管理,故之后添加依赖无需指定version -->
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Camden.SR2</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
		<!-- 用以为integration-test提供支持。 -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Cloud Hystrix是一个用于处理分布式系统的延迟和容错的库。它通过隔离服务之间的访问点,防止级联故障,并提供了一个备用方案,以便在出现故障时继续运行。Hystrix通过实现断路器模式来实现这些功能,这意味着它可以在服务之间建立一个断路器,以便在服务出现故障时自动切换到备用方案。 ### 回答2: Spring Cloud Hystrix是基于Netflix Hystrix的容错框架,为微服务提供了服务降级、服务熔断、服务限流等容错机制,以确保微服务在面临异常情况时,能够保持高可用性和稳定性。 在微服务架构中,服务之间的调用很容易受到网络波动、服务不可用、资源限制等影响,这时候如果不进行容错处理,就可能会导致整个系统崩溃。Spring Cloud Hystrix通过引入断路器的概念,可以提供一种优雅的容错处理方式。当某个服务出现故障或延迟时,断路器会立刻打开,停止对该服务的调用,降低对该服务的压力,保持系统的稳定性。 除了断路器外,Spring Cloud Hystrix还提供了线程池隔离、信号量隔离、缓存预处理等机制,以更好地保护系统。如果采用线程隔离,可以让请求在独立的线程中执行,从而防止请求的问题影响到其他请求。信号量隔离通过限制并发数,达到在负载高峰期或请求过多时,自我调节的目的。 在使用方面,Spring Cloud Hystrix也非常简单。只需在服务调用处添加@HystrixCommand注解,指定服务降级方法,就可以完成调用端的服务降级处理。对于其他Hystrix特性,也可以通过在配置文件中进行配置。 总而言之,Spring Cloud Hystrix为微服务架构提供了一种高效可靠的容错机制,可以在服务出现问题时,从容松手,保证系统的鲁棒性和扩展性。 ### 回答3: Spring Cloud Hystrix是一种开源的断路器模式实现,可用于构建分布式系统和微服务。它可以防止由于一个服务故障或超时导致整个系统崩溃。 在分布式系统中,一个服务的故障可能会导致整个系统的连锁反应。这就是为什么需要HystrixHystrix可以监视服务调用的结果,如果服务出现故障,它会强制断路器并替代其他服务并返回一个错误响应。 服务故障可能不仅仅是由于服务器故障,还包括超时,网络故障等原因。Hystrix 可以配置降级策略,当服务出现故障时,可以返回一些默认值或者备用数据,使得服务的调用方不至于完全失败。如果这些降级策略的执行时间过长,超出了阈值,那么Hystrix会自动熔断该服务,以免该服务继续产生故障影响到整个系统。 Hystrix可以同时监控多个服务,以避免整个系统受到单个服务故障的影响。如果某个服务出现问题,Hystrix会自动将该服务的请求转向其他可用的服务,以确保业务服务的高可用性。 在开发过程中,Hystrix虽然具有强大的监控能力,但同时也需要注意它会增加系统的负担,因此需要根据需求进行合理的配置。使用Hystrix需要在Spring Cloud应用中增加相应的依赖,同时在应用代码中使用@HystrixCommand注解对需要监控的服务进行定义。对服务的降级策略可以通过@Service注解中的fallback属性来定义。 总之,Hystrix提供了一种有力的方式来保证服务调用的稳定性,并确保系统的高可用性。它使得微服务架构更加健壮和高效。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值