springcloud-hystrix circuit breaker practice
1. Brief introduction
Hystrix is a latency and fault-tolerant library designed to isolate access points to remote systems, services and third-party libraries, stop cascading failures, and achieve resilience in complex distributed systems where failures are inevitable.
2. Springboot integrated hystrix fusing practice
1. Import dependencies
<!-- hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.4.6.RELEASE</version>
</dependency>
2. Method of writing circuit breaker
First of all, this is the code located in the service provider. When the hello method throws an exception, it uses the annotation @HystrixCommand(fallbackMethod = "Hystrix") to call the Hystrix method
@RequestMapping("/findById")
@HystrixCommand(fallbackMethod = "Hystrix")
public User hello(Long id){
User user = userService.findById(id);
if (user==null){
throw new RuntimeException("id => " + id + ",不存在该用户,或者信息无法找到");
}
return user;
}
//备选方法
public User Hystrix(Long id){
return new User()
.setId(id)
.setName("id => " + id + ",不存在该用户,或者信息无法找到")
.setDb("no db ");
}
3. Start the project in the startup class to support the fuse
@EnableCircuitBreaker means adding support for circuit breaker
package com.hzxy.springcloud;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@MapperScan("com.hzxy.springcloud.mapper")
@EnableDiscoveryClient //服务发现
@EnableEurekaClient //在服务启动后自动注册到Eureka中
@SpringBootApplication
@EnableCircuitBreaker //添加对熔断的支持
public class HystrixProvider_8001 {
public static void main(String[] args) {
SpringApplication.run(HystrixProvider_8001.class,args);
}
}
3. Test
Access the data contained in the database, it finds the result
When accessing data that the database does not have, it will execute the alternate method, as follows: The
test is successful!