Make writing a habit together! This is the fifth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

At present, there are two main service circuit breaker downgrading schemes: Hystrix of SpringCloud and Sentinel of Alibaba. Sentinel has absolute advantages in terms of overall popularity, user experience and rich functions.

Why is a service circuit breaker needed?

In the current microservice architecture, there are multiple services and the invocation between them is complex. When one service fails, the service cannot be invoked. At this time, traffic will accumulate in the whole system and eventually make the whole system unusable. The circuit breaker of the service used is important to maintain system problems and availability.

Two points should be paid attention to in fusing: starting fusing and resuming fusing.

What is service degradation?

When the system encounters a traffic peak in a certain period of time, the pressure on the entire system increases. In this case, to ensure the running of core services, you can restrict or stop the access to some irrelevant services and pages to release the overall pressure on the server.

Let’s demonstrate Hystrix separately.

Hystrix

The code

Introducing dependencies:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <version>2.23..RELEASE</version>
        </dependency>
Copy the code

Add the comment @enablecircuitbreaker to enable the fuses. Here I demonstrate the project using gateway:

/** * Start class **@author weirx
 */
@EnableCircuitBreaker
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}, scanBasePackages = {"com.cloud.bssp.gateway"})
@EnableFeignClients(basePackages = {"com.cloud.bssp.gateway.feign"})
public class BsspGatewayApplication {

    public static void main(String[] args) { SpringApplication.run(BsspGatewayApplication.class, args); }}Copy the code

By default, Hystrix is disabled in FeignClient by default. Therefore, if you want to enable the Hystrix fusing function in microservices, you need to manually enable Hystrix by configuring:

# Hystrix feign: hystrix: enabled:true
Copy the code

Provide a feignClient for the user service, with an emphasis on the property fallbackFactory, followed by the configuration of the current feignClient implementation class.

@FeignClient(name = "bssp-user-service", path = "/user",fallbackFactory = UserClientImpl.class)
public interface UserClient {

    @PostMapping("/login")
    R login(@RequestBody UserDTO userDTO);
}
Copy the code

For example, add the @Component annotation to the UserClientImpl code, otherwise you may report an error that the service cannot be found:

/ * * *@author weirx
 * @date"2021/07/08 * * /
@Slf4j
@Component
public class UserClientImpl implements FallbackFactory<UserClient> {
    @Override
    public UserClient create(Throwable throwable) {
        return new UserClient() {
            @Override
            public R login(UserDTO userDTO) {
                log.info("Failed to invoke user service. Degraded user service processing.");
                return R.failed("Failed to invoke user service, degraded user service processing"); }}; }}Copy the code

When the user service is down, the login interface is used for convenience. Shut down the user service or process it offline in the registry. View the results:

Histrix provides panels for us to view intuitively: HystrixDashboard introduces dependencies. It is important to note that you should not add dashboards to springcloudGateway, because its dependencies contain Web components, which will conflict with gateway.

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
            <version>2.23..RELEASE</version>
        </dependency>
Copy the code

Add an annotation @enablehystrixDashboard to the startup class

/ * * *@author weirx
 * @description: Data service startup class * <p> * annotations@ServletComponentScan: Enables servlets, filters, and listeners to pass@WebServlet.@WebFilter.@WebListener* Such annotations are registered directly without additional code *@date2020/6/17 * /
@EnableHystrixDashboard
@EnableCircuitBreaker
@SpringBootApplication
@ServletComponentScan
@EnableFeignClients
public class BsspAdminServiceApplication {

    public static void main(String[] args) { SpringApplication.run(BsspAdminServiceApplication.class, args); }}Copy the code

The results show

Go to http://localhost:8080/hystrix

Here are my client and Fallback implementations:

/** * Create Date: 2021-03-17T13:53:59.025 * Modified By: < BR > * Modified Date: < BR > * Why & What is Modified: < BR > * *@author weirx
 * @version1.0 * /
@FeignClient(name = "bssp-user-service", path = "/user", fallbackFactory = UserClientImpl.class)
public interface UserClient {

    /** ** paged list **@param params
     * @return* /
    @PostMapping("/pageList")
    R pageList(@RequestBody Map<String, Object> params);

    /** * list **@param userDTO
     * @return* /
    @PostMapping("/list")
    R list(@RequestBody UserDTO userDTO);

    /** * select * from primary key@param id
     * @return* /
    @GetMapping("/info/getById")
    R info(@RequestParam("id") Long id);

    /**
     * 新增
     *
     * @param userDTO
     * @return* /
    @PostMapping("/save")
    R save(@RequestBody UserDTO userDTO);

    /** * update **@param userDTO
     * @return* /
    @PostMapping("/update")
    R update(@RequestBody UserDTO userDTO);
}
Copy the code
import java.util.Map;

/ * * *@author weirx
 * @date 2021/07/08 14:38
 **/
@Component
public class UserClientImpl implements FallbackFactory<UserClient> {
    @Override
    public UserClient create(Throwable throwable) {
        return new UserClient() {
            @Override
            public R pageList(Map<String, Object> params) {
                return R.failed("Failed to invoke user service, service has been degraded");
            }

            @Override
            public R list(UserDTO userDTO) {
                return R.failed("Failed to invoke user service, service has been degraded");
            }

            @Override
            public R info(Long id) {
                return R.failed("Failed to invoke user service, service has been degraded");
            }

            @Override
            public R save(UserDTO userDTO) {
                return R.failed("Failed to invoke user service, service has been degraded");
            }

            @Override
            public R update(UserDTO userDTO) {
                return R.failed("Failed to invoke user service, service has been degraded"); }}; }}Copy the code

Test controller:

@API (tags = "Testing Hystrix")
@RestController
@RequestMapping("/test")
public class TestController {

    /** * SysMenuService */
    @Autowired
    private UserClient userClient;


    /** * list list *@return* /
    @GetMapping("/list")
    public R list(a) {
        return userClient.list(newUserDTO()); }}Copy the code

Color description:

Now monitor the service through Dashboard. When the user service starts normally, we visit the port several times to see the result:

When we turn the service off after access to see the results: