Hystrix fuse downgrade solution

Get into the habit of writing together! This is the 5th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

At present, there are two main service fuse and downgrade solutions: springcloud Hystrixand Alibaba Sentinel. Sentinel has absolute advantages in terms of overall popularity, user experience, and rich functions.

Why do you need a circuit breaker for services?

The current microservice architecture has multiple services, and the calls to each other are complicated. When a service fails and the service cannot be called, when the traffic comes up, it will cause the traffic of the entire system to accumulate, eventually causing the entire system to be unavailable. . The circuit breaker of the service used is very important to maintain the problem and availability of the system.

There are two main points of attention for fusing: start fusing and recovery fusing.

What is service downgrade?

When the system ushered in a traffic peak in a certain period of time, the pressure on the entire system doubled. At this time, in order to ensure the operation of the core business, the traffic of some insignificant services and pages can be restricted or stopped, thereby releasing the overall server. pressure.

Below we demonstrate the use of Hystrix respectively.

Hystrix

code writing

Import dependencies:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>
复制代码

Add the annotation @EnableCircuitBreaker to turn on the circuit breaker. I will use the gateway to demonstrate the project here:

/**
 * 启动类
 *
 * @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);
    }

}
复制代码

By default, Hystrix is ​​disabled in FeignClient by default, so if you need to enable the fuse function of Hystrix in microservices, you need to manually enable the Hystrix function through configuration:

#开启hystrix
feign:
  hystrix:
    enabled: true
复制代码

Provide a feignClient for user services, focusing on the attribute fallbackFactory , and then configure the implementation class of the current feignClient.

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

    @PostMapping("/login")
    R login(@RequestBody UserDTO userDTO);
}
复制代码

For example, in UserClientImpl code, pay attention to adding the @Component annotation, otherwise an error that the service cannot be found may be reported:

/**
 * @author weirx
 * @date 2021/07/08 11:10
 **/
@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("调用用户服务失败,对用户服务降级处理。");
                return R.failed("调用用户服务失败,对用户服务降级处理");
            }
        };
    }
}
复制代码

The login interface is used for the convenience of accessing the login interface when the simulated user service is down. Shut down the user service, or go offline in the registry. View Results:

image.png

Histrix provides a panel for us to view intuitively: HystrixDashboard, which introduces dependencies. It should be noted that try not to add dashboards to springcloudGateway, because its dependencies contain web components, which will conflict with gateways, so I will change a service in the following demonstration. I stepped on a pit myself:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>
复制代码

Add the annotation @EnableHystrixDashboard to the startup class

/**
 * @author weirx
 * @description: 数据服务启动类
 * <p>
 * 注解@ServletComponentScan: 使Servlet,filter,listener 可以通过 @WebServlet,@WebFilter,@WebListener
 * 等注解直接注册,无需其他代码
 * @date 2020/6/17
 */
@EnableHystrixDashboard
@EnableCircuitBreaker
@SpringBootApplication
@ServletComponentScan
@EnableFeignClients
public class BsspAdminServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(BsspAdminServiceApplication.class, args);
    }
}
复制代码

Results display

Visit http://localhost:8080/hystrix

image.png

Below is my client and fallback implementation:

/**
 * Description: 用户表
 * Create Date: 2021-03-17T13:53:59.025
 * Modified By:<br>
 * Modified Date:<br>
 * Why & What is modified:<br>
 *
 * @author weirx
 * @version 1.0
 */
@FeignClient(name = "bssp-user-service", path = "/user", fallbackFactory = UserClientImpl.class)
public interface UserClient {

    /**
     * 分页列表
     *
     * @param params
     * @return
     */
    @PostMapping("/pageList")
    R pageList(@RequestBody Map<String, Object> params);

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

    /**
     * 根据主键查询
     *
     * @param id
     * @return
     */
    @GetMapping("/info/getById")
    R info(@RequestParam("id") Long id);

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

    /**
     * 更新
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/update")
    R update(@RequestBody UserDTO userDTO);
}
复制代码
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("调用用户服务失败,服务已被降级处理");
            }

            @Override
            public R list(UserDTO userDTO) {
                return R.failed("调用用户服务失败,服务已被降级处理");
            }

            @Override
            public R info(Long id) {
                return R.failed("调用用户服务失败,服务已被降级处理");
            }

            @Override
            public R save(UserDTO userDTO) {
                return R.failed("调用用户服务失败,服务已被降级处理");
            }

            @Override
            public R update(UserDTO userDTO) {
                return R.failed("调用用户服务失败,服务已被降级处理");
            }
        };
    }
}
复制代码

Test controller:

@Api(tags = "测试Hystrix")
@RestController
@RequestMapping("/test")
public class TestController {

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


    /**
     * list列表
     * @return
     */
    @GetMapping("/list")
    public R list() {
        return userClient.list(new UserDTO());
    }

}
复制代码

Color description:

image.png

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

image.png

When we turn off the service, visit to see the results:

image.png

Guess you like

Origin juejin.im/post/7082937455157968926