19. 모니터링 Hystrix 대시 보드 [광고 시스템의 단계를 구현하여 봄 클라우드 단계]

18 개 이전 기사에서, 우리는 광고 시스템 구현 广告投放, 广告检索비즈니스 기능을에 중간을 사용 服务发现Eureka, 服务调用Feign, 网关路由Zuul错误熔断Hystrix기타 Spring Cloud구성 요소.
단순히 관계를 호출
UTOOLS1565828973486.png

우리의 서비스보다 직관적 호출 한 후, 다음에 일어날하지만 어떻게 시스템이 종종 우리가 내결함성 클래스와 메소드를 정의 오류하지만 당신은 단지 콘솔에 오류 메시지를 볼 수 있습니다, 우리가 볼 수있는 통계 데이터의 일부를 원하는 그리고 우리는 새로운 퓨즈 모니터링 구성 요소를 논의 Hystrix Dashboard우리가 말할 수있는 이름에서, 그것은 그래픽 인터페이스를 모니터하는 것입니다, 정의,.

서비스에 Hystrix 사용

함께의 openfeign에 사용

대부분과 함께 사용되어 우리의 실제 프로젝트에서 FeignClient#fallbackHystrix퓨즈를 달성하기 위해 함께 작동, 우리는 우리의보고 mscx-ad-feign-sdk구현입니다.

@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);
}

위의 코드에서, 우리는 사용자 정의 feignclient 있고, 클라이언트에게 대체 구현 클래스를했다 :

@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.");
    }
}

폴백 클래스는 우리의 사용자 정의를 구현하는 ISponsorFeignClient대체 방법은 원래의 클래스와 메소드 서명이 일치 수행해야하기 때문에 실패가 실행되면, 응답 / 결함 허용 방법을 다운 그레이드 반사 방법으로 매핑 할 수 있도록이입니다.
에서 mscx-ad-search서비스, 사출에 의해 우리는 ISponsorFeignClient우리의 호출 mscz-ad-sponsor서비스를.

@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;
    }
}
용도HystrixCommand

사실, Hystrix 자체가 법에 직접 적용하는 방법을 사용하는 것입니다 제공합니다 @ com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand우리는이 클래스의 소스 코드를 보면 :

@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 "";

    ...
}

우리는 두 가지 점에 초점 :

  1. @Target({ElementType.METHOD})그것은 현재의 방법은 위의에 적용 할 수 있음을 지적한다.
  2. 직접 정의 할 수 있습니다 fallbackMethod내결함성을 보장하기 위해. 이 방법은 우리의 접근 실현 될 것 같은 클래스 파일에서의 메소드를 실행해야 결함을 갖고, 특히 이중화 우아이다.

우리와 mscx-ad-search예를 들어 광고 쿼리 :

@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) {
        ...
    }
}

우리가 잘못 물어 보면, 우리의 대체 방법으로 이동합니다,이 응용 프로그램 시작에 의해 달성된다, 우리가 시작 @EnableCircuitBreaker주석을, 모든 AOP 요격에 의해 주석 HystrixCommand방법은 것 HystrixCommandspringboot 컨테이너에 통합 될 고장이 대체 방법을 호출하는 반사에 의해 달성되면 방법은 hystrix 스레드로 주석이 주석.

대시 보드 프로젝트를 만듭니다

우리가 Hystrix 두 가지 방법의 융합 달성 보였다 코드는, 우리는, 그래픽 인터페이스를 모니터링 요청을 수행 만들어야 할 mscx-ad-dashboard,하자의 코드를.
여전히 우리의 springboot 부작 프로젝트를 준수 :

  1. 플러스 의존

    <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. 코멘트를 추가

    /**
       * 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. 변경 구성

        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: "*"`

직접 기동은 다음 페이지를 참조하십시오 :
UTOOLS1565833851940.png

모니터링 할 수있는 서비스 주소를 추가합니다 :
UTOOLS1565833920702.png

추천

출처www.cnblogs.com/zhangpan1244/p/11361078.html