[Spring cloud step by step implementation of the ad system] 19. Monitoring Hystrix Dashboard

In 18 previous articles, we realized the advertising system 广告投放, 广告检索business functions, use the middle to the 服务发现Eureka, 服务调用Feign, 网关路由Zuuland 错误熔断Hystrixand other Spring Cloudcomponents.
Simply call the relationship:
UTOOLS1565828973486.png

But the system often will error, we defined a number of fault tolerance classes and methods, but you can only see an error message on the console, we want some of the statistical data, to see how our services more intuitive call happens then, next , and we discuss a new fuse monitoring component Hystrix Dashboard, by definition, from the name we can tell, it is to monitor the graphical interface.

Hystrix use in the service

Use in conjunction openfeign

In our actual project which, most is used in conjunction with FeignClient#fallbackand Hystrixwork together to achieve the fuse, we look at our mscx-ad-feign-sdkimplementation.

@FeignClient(value = "mscx-ad-sponsor", fallback = SponsorClientHystrix.class)
public interface ISponsorFeignClient {
    @RequestMapping(value = "/ad-sponsor/plan/get", method = RequestMethod.POST)
    CommonResponse<List<AdPlanVO>> getAdPlansUseFeign(@RequestBody AdPlanGetRequestVO requestVO);

    @RequestMapping(value = "/ad-sponsor/user/get", method = RequestMethod.GET)
    /**
     * Feign 埋坑之 如果是Get请求,必须在所有参数前添加{@link RequestParam},不能使用{@link Param}
     * 会被自动转发为POST请求。
     */
    CommonResponse getUsers(@RequestParam(value = "username") String username);
}

In the above code, we have a customized feignclient, and gave the client a fallback implementation class:

@Component
public class SponsorClientHystrix implements ISponsorFeignClient {
    @Override
    public CommonResponse<List<AdPlanVO>> getAdPlansUseFeign(AdPlanGetRequestVO requestVO) {
        return new CommonResponse<>(-1, "mscx-ad-sponsor feign & hystrix get plan error.");
    }

    @Override
    public CommonResponse getUsers(String username) {
        return new CommonResponse<>(-1, "mscx-ad-sponsor feign & hystrix get user error.");
    }
}

The fallback class implements our custom ISponsorFeignClient, it is because the fallback method must perform original class and method signatures consistent, so that when the failure to execute, can be mapped by the reflection method to downgrade the response / fault-tolerance method.
In mscx-ad-searchservices, we by injection ISponsorFeignClientto call our mscz-ad-sponsorservice.

@RestController
@Slf4j
@RequestMapping(path = "/search-feign")
public class SearchFeignController {

    /**
     * 注入我们自定义的FeignClient
     */
    private final ISponsorFeignClient sponsorFeignClient;
    @Autowired
    public SearchFeignController(ISponsorFeignClient sponsorFeignClient) {
        this.sponsorFeignClient = sponsorFeignClient;
    }

    @GetMapping(path = "/user/get")
    public CommonResponse getUsers(@Param(value = "username") String username) {
        log.info("ad-search::getUsersFeign -> {}", JSON.toJSONString(username));
        CommonResponse commonResponse = sponsorFeignClient.getUsers(username);
        return commonResponse;
    }
}
useHystrixCommand

In fact, Hystrix itself provides a way of direct application in the method is to use @ com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand, we look at the source code for this class:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface HystrixCommand {
    ...

        /**
     * Specifies a method to process fallback logic.
     * A fallback method should be defined in the same class where is HystrixCommand.
     * Also a fallback method should have same signature to a method which was invoked as hystrix command.
     * for example:
     * <code>
     *      @HystrixCommand(fallbackMethod = "getByIdFallback")
     *      public String getById(String id) {...}
     *
     *      private String getByIdFallback(String id) {...}
     * </code>
     * Also a fallback method can be annotated with {@link HystrixCommand}
     * <p/>
     * default => see {@link com.netflix.hystrix.contrib.javanica.command.GenericCommand#getFallback()}
     *
     * @return method name
     */
    String fallbackMethod() default "";

    ...
}

We focus on two points:

  1. @Target({ElementType.METHOD})It notes that the current method can only be applied in the above.
  2. It can be directly defined fallbackMethodto ensure fault tolerance. This method has a defect that must execute a method in the same class file, which will result in the realization of our approach, and is particularly redundancy and inelegant.

With our mscx-ad-searchads query as an example:

@Service
@Slf4j
public class SearchImpl implements ISearch {

    /**
     * 查询广告容错方法
     *
     * @param e 第二个参数可以不指定,如果需要跟踪错误,就指定上
     * @return 返回一个空map 对象
     */
    public SearchResponse fetchAdsFallback(SearchRequest request, Throwable e) {

        System.out.println("查询广告失败,进入容错降级 : %s" + e.getMessage());
        return new SearchResponse().builder().adSlotRelationAds(Collections.emptyMap()).build();
    }

    @HystrixCommand(fallbackMethod = "fetchAdsFallback")
    @Override
    public SearchResponse fetchAds(SearchRequest request) {
        ...
    }
}

When we ask wrong, will go to our fallback method, this is achieved by the application startup, we started @EnableCircuitBreakerannotation, the annotations by all AOP intercept HystrixCommandmethod, will HystrixCommandbe integrated into springboot container, and methods annotated annotated into hystrix threads, once the failure to achieve by reflection to invoke fallback method.

Create a dashboard project

The code we looked Hystrix achieve fusing of two ways, then we have to fulfill the request monitoring graphical interface, create mscx-ad-dashboard, Let's code.
Still comply with our springboot trilogy project:

  1. Plus dependence

    <dependencies>
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-hystrix</artifactId>
             <version>1.2.7.RELEASE</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
             <version>1.2.7.RELEASE</version>
         </dependency>
         <!--eureka client-->
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-actuator</artifactId>
         </dependency>
     </dependencies>
  2. Add comment

    /**
       * AdDashboardApplication for Hystrix Dashboard 启动类
       *
       * @author <a href="mailto:[email protected]">Isaac.Zhang | 若初</a>
       * @since 2019/8/15
       */
        @SpringBootApplication
        @EnableDiscoveryClient
        @EnableHystrixDashboard
        public class AdDashboardApplication {
    
            public static void main(String[] args) {
                SpringApplication.run(AdDashboardApplication.class, args);
            }
        }
  3. Change configuration

        server:
            port: 1234
        spring:
            application:
                name: mscx-ad-dashboard
        eureka:
            client:
                service-url:
                defaultZone: http://server1:7777/eureka/,http://server2:8888/eureka/,http://server3:9999/eureka/
        management:
            endpoints:
                web:
                exposure:
                    include: "*"`

Direct start, see the following page:
UTOOLS1565833851940.png

Add the service address to be monitored:
UTOOLS1565833920702.png

Guess you like

Origin www.cnblogs.com/zhangpan1244/p/11361078.html