Start a spring cloud project - Step 6 Feign declarative interface call and circuit breaker implementation using Hystrix

Feign

  • What is Feign

Feign Like Ribbon, Feign is also provided by Netflix. Feign is a declarative and modular Web Service client. It simplifies the operation of developers to write Web service clients. Developers can call HTTP through simple interfaces and annotations. API, Spring Cloud Feign, integrates Ribbon and Hystrix, and has a series of convenient functions such as pluggable, annotation-based, load balancing, and service breaker.

Compared with the Ribbon + RestTemplate method, Feign greatly simplifies code development. Feign supports a variety of annotations, including Feign annotations, JAX-RS annotations, Spring MVC annotations, etc. Spring Cloud has optimized Feign and integrated Ribbon and Eureka , thus making Feign more convenient to use.

  • The difference between Ribbon and Feign

    1. Fiegn is a declarative Web Service client.
    2. Supports Feign annotations, Spring MVC annotations, and JAX-RS annotations.
    3. Feign is implemented based on Ribbon, making it easier to use.
    4. Feign integrates Hystrix and has the function of service circuit breaker.

Turn on Feign's function

1. Create a new Module, name it feign, add the following dependencies to pom.xml

<dependencies>
    <!-- 都是作为服务注册到Eureka Server ,所以需要添加这个依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>2.0.2.RELEASE</version>
    </dependency>
    <!-- Feign 的依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
        <version>2.0.2.RELEASE</version>
    </dependency>
</dependencies>

2. Create a new application.yml file
with the following content:

server:
  port: 8050
spring:
  application:
      name: feign
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

3. Create a startup class and add Feign-related annotations.
Name the startup class FeignApplication and
the code is as follows:

package com.southwind;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

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

4. Because we still need to continue to operate the student entity class created in the first article, we need to copy the original entity class code to
the Student class:

package com.southwind.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor                 //无参构造
@AllArgsConstructor                //有参构造
public class Student {
    
    
    private long id;
    private String name;
    private int age;

}

The directory structure is as follows:
Insert image description here

4. Create a new interface named FeignProviderClient and place it in the com.southwind.feign package.

The FeignProviderClient code is as follows:


```java
package com.southwind.feign;

import com.southwind.entity.Student;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Collection;

//这里就体现了Feign 的声明式调用,都是接口,
//value = provider是因为提供者在注册中心的名字叫做 provider
@FeignClient(value = "provider")
public interface FeignProviderClient {
    
    
   /* 需要调用提供者的controller 里面的方法,直接就行(有
    * 点相当于它自己就会把provider 替换成IP地址,然后把Mapping 里面的值给拼接
    * 到后面,实现模块间的调用。)
    */
    @GetMapping("/student/findAll")
    public Collection<Student> findAll();
    @GetMapping("/student/index")
    public String index();
}

5. Create a controller, name it FeignHandler.java, and store it in the com.southwind.controller folder.

package com.southwind.controller;

import com.southwind.entity.Student;
import com.southwind.feign.FeignProviderClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
@RequestMapping("/feign")
public class FeignHandler {
    
    
    @Autowired
    private FeignProviderClient feignProviderClient;

    @GetMapping("/findAll")
    public Collection<Student> findAll(){
    
    
        return feignProviderClient.findAll();
    }

    @GetMapping("/index")
    public String index(){
    
    
        return feignProviderClient.index();
    }
}

6. Start the registration center eruekaserver, and then, like the previous article, one project starts provider services for two different ports, starts eurekaclient, and then starts the feign project

7. Enter in the browser: localhost:8050/feign/index

Insert image description here

Insert image description here
Insert image description here
Insert image description here

Feign declarative calling can also achieve load balancing, and it simplifies the code and is more convenient than using the zuul gateway method.

Use Feign to realize service circuit breaker

What is a circuit breaker.
When microservices handle flash sale scenarios, or similar scenarios, resulting in extremely large concurrent access to the server, a service may crash, causing the service that calls it to crash because it cannot wait for a response from the service for a long time. In this way, By analogy, leading to the "avalanche effect". At this time, the fuse comes into play. It is like a fuse in a circuit. Once the current exceeds the maximum current, the fuse will cut off the power to prevent leakage and electric shock. When a service continues to be called without responding, the circuit breaker is activated, temporarily stopping access to the service, and returning a circuit breaker result to inform the user to try again later. Wait for the downed service to return to normal. After the service can be accessed normally, the fuse is automatically closed.

1. In the yml file of the original feign project, add the code to enable feign fuse.

server:
  port: 8050
spring:
  application:
    name: feign
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
feign:
  hystrix:
    enabled: true

feign.hystrix.enabled: true whether to turn on the fuse

2. Create the FeignError implementation class of FeignProviderClient, define the fault-tolerant processing logic, and inject the FeignError instance into the IoC container through the @Component annotation.

Insert image description here
FeignError code:

package com.southwind.feign.impl;

import com.southwind.entity.Student;
import com.southwind.feign.FeignProviderClient;
import org.springframework.stereotype.Component;

import java.util.Collection;
@Component
public class FeignError implements FeignProviderClient {
    
    
    @Override
    public Collection<Student> findAll() {
    
    
        return null;
    }
//当熔断开启时,停止对该服务的访问,然后调用此方法告知用户系统繁忙
    @Override
    public String index() {
    
    
        return "服务器维护中.....";
    }
}

3. Set mapping through the fallback attribute of @FeignClient at the definition of FeignProviderClient and perform downgrade processing.

In FeignProviderClient, add downgrade processing (red frame part).
Insert image description here
At this time, once Feign accesses the service provider, if the service provider is not in a normal state and feign access is unsuccessful, he will find the fallback method in feignError to handle it. In this way, web page status codes such as 500, 404, etc. will not appear, but the fallback you wrote, that is, the circuit breaker processing method, will appear.

4. Test

First stop the service provider. At this time, use feign to call the provider, and a 500 will be reported, that is, the server is not responding.
Insert image description here

Restart feign at this time (after turning on the feign circuit breaker, it has not taken effect yet. Now restart feign to make the circuit breaker take effect)

Re-visit in the browser: localhost:8050/feign/index

Insert image description here
The fuse was activated successfully. Because the provider cannot be adjusted, it directly calls its own circuit breaker method.

Guess you like

Origin blog.csdn.net/chenmaolin928/article/details/109184353