Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Spring Cloud getting started tutorial-Hystrix Circuit Breaker for Fault tolerance and degradation

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

Brief introduction

Spring cloud provides a Hystrix fault-tolerant library to implement a downgrade policy for methods configured with circuit breakers and temporarily invoke alternate methods when the service is unavailable. This article will create a product microservice, register with the eureka service registry, then we use web client access / products API to get the product list, and when the product service fails, call the local alternate method to downgrade but provide the service normally.

Basic environment JDK 1.8Maven 3.3.9IntelliJ 2018.1Git project source code

Gitee Code Cloud

Add products and services

Create a new maven project in intelliJ with the following configuration

GroupId: cn.zxuqianartifactId: productService

Then add the following code to pom.xml:

4.0.0 cn.zxuqian productService 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.0.1.RELEASE UTF-8 1.8 org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud Spring-cloud-starter-config org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies Finchley.M9 pom import org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring . io/libs-milestone false

We continued to use spring-cloud-starter-netflix-eureka-client to automatically register the product service with the eureka service. Then spring-cloud-starter-config is used to read the configuration file of the configuration service center. This project is just a simple spring web project.

Create a bootstrap.yml file under src/main/resources and add the following:

Spring: application: name: product-service cloud: config: uri: http://localhost:8888

Create a product-service.yml file in the git repository in the configuration center to add the following configuration and submit:

Server: port: 8081

This configuration specifies a port of 8081 for the product service. Then create the Application class and add the following code:

Package cn.zxuqian;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@EnableDiscoveryClient@SpringBootApplicationpublic class Application {public static void main (String [] args) {SpringApplication.run (Application.class, args);}}

The @ EnableDiscoveryClient annotation instructs spring cloud to automatically register this service with eureka. Finally, create a cn.zxuqian.controllers.ProductController controller, provide / products API, and return sample data:

Package cn.zxuqian.controllers;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class ProductController {@ RequestMapping ("/ products") public String productList () {return "coat, jacket, sweater, T-shirt";} configure Web client

Open the web project we created earlier and add a new Hystrix dependency to pom.xml:

Org.springframework.cloud spring-cloud-starter-netflix-hystrix

Then update the code for the Application class:

Package cn.zxuqian;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.web.client.RestTemplateBuilder;import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.context.annotation.Bean;import org.springframework.web.client.RestTemplate;@EnableCircuitBreaker@EnableDiscoveryClient@SpringBootApplicationpublic class Application {public static void main (String [] args) {SpringApplication.run (Application.class, args) @ Bean public RestTemplate rest (RestTemplateBuilder builder) {return builder.build ();}}

Here you use @ EnableCircuitBreaker to turn on the circuit breaker, and then add a rest method and use the @ Bean annotation. This part is part of the Spring dependency injection feature, and the method using the @ Bean tag tells you how to initialize such objects, such as creating an RestTemplate object using RestTemplateBuilder in this case, which is later used in service using circuit breakers.

Create the cn.zxuqian.service.ProductService class and add the following code:

Package cn.zxuqian.services;import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cloud.client.ServiceInstance;import org.springframework.cloud.client.discovery.DiscoveryClient;import org.springframework.stereotype.Service;import org.springframework.web.client.RestTemplate;import java.util.List;@Servicepublic class ProductService {private final RestTemplate restTemplate; @ Autowired private DiscoveryClient discoveryClient; public ProductService (RestTemplate restTemplate) {this.restTemplate = restTemplate } @ HystrixCommand (fallbackMethod = "backupProductList") public String productList () {List instances = this.discoveryClient.getInstances ("product-service"); if (instances! = null & & instances.size () > 0) {return this.restTemplate.getForObject (instances.get (0). GetUri () + "/ products", String.class);} return "" } public String backupProductList () {return "jacket, sweater";}}

You create a Service class because Hystrix can only be used in classes marked @ Service or @ Component so that the API provided by Spring Context can be used properly. I will explain this later when I go deep into Spring. After annotated with `@ HystrixCommand`, Hystrix will monitor the annotated method, namely `productList` (the bottom layer uses proxy to wrap this method to achieve monitoring). Once the errors of this method accumulate to a certain threshold, the circuit breaker will be activated, and all subsequent requests for calling the `productList` method will fail, and the method `productList` specified by `fallbackMethod` will be temporarily called. Then, when the service returns to normal, the circuit breaker will be shut down. Br/ > after annotated with `@ HystrixCommand`, Hystrix will monitor the annotated method, namely `productList` (the bottom layer uses proxy to wrap this method to achieve monitoring). Once the errors of this method accumulate to a certain threshold, the circuit breaker will be activated, and all subsequent requests for calling the `productList` method will fail, and the method `productList` specified in `fallbackMethod` will be temporarily called. Then, when the service returns to normal, the circuit breaker will be shut down.

DiscoveryClient is used to find the uri address of the product service, using the value of the spring.application.name configuration item of the product service, that is, product-service is passed to the discoveryClient.getInstances () method as serviceID, and then a list is returned. Because we only have one product service started, we only need to take the uri address of the first instance.

Then we use RestTemplate to access the api of the product service. Note that the constructor injection of Spring is used here, that is, the method we annotated with @ Bean before will be used to initialize the restTemplate variable, without the need for us to initialize it manually. The RestTemplate class provides the getForObject () method to access other Rest API and wrap the result in the form of an object. The first parameter is the uri address of the api to be accessed, and the second parameter is the type of result obtained. Here we return String, so pass it to him String.class.

The backupProductList () method returns the degraded product list information.

Finally, create a controller cn.zxuqian.controllers.ProductController and add the following code:

Package cn.zxuqian.controllers;import cn.zxuqian.services.ProductService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class ProductController {@ Autowired private ProductService productService; @ RequestMapping ("/ products") public String productList () {return productService.productList ();}}

ProductService is used here to provide data for the / products path.

test

First, we use the spring-boot:run plug-in to start the configuration center service, config-server, then start eureka-server, then start product-service, and finally start the web client. Wait a moment after the eureka service is registered and visit http://localhost:8080/products. Normally, we will get the coat, jacket, sweater, T-shirt results, and then we will close product-service, and then access the same path. You'll get the result of the downgrade: jacket, sweater.

Welcome to my blog http://zxuqian.cn/spring-cloud-tutorial-hystrix/.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report