com.xyxy.platform.examples.showcase.demos.hystrix.service.GetUserCommand.java Source code

Java tutorial

Introduction

Here is the source code for com.xyxy.platform.examples.showcase.demos.hystrix.service.GetUserCommand.java

Source

/*******************************************************************************
 * Copyright (c) 2005, 2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.xyxy.platform.examples.showcase.demos.hystrix.service;

import com.xyxy.platform.examples.showcase.webservice.rest.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.exception.HystrixBadRequestException;

/**
 * HystrixCommand, ??T run().
 * , , ?T getFallback().
 * 
 *
 */
public class GetUserCommand extends HystrixCommand<UserDTO> {

    private static Logger logger = LoggerFactory.getLogger(GetUserCommand.class);

    private RestTemplate restTemplate;
    private Long id;

    /**
     * ????.
     */
    protected GetUserCommand(Setter commandConfig, RestTemplate restTemplate, Long id) {
        super(commandConfig);
        this.restTemplate = restTemplate;
        this.id = id;
    }

    /**
     * ??
     */
    @Override
    protected UserDTO run() throws Exception {
        try {
            logger.info("Access restful resource");
            return restTemplate.getForObject("http://localhost:8080/showcase/hystrix/resource/{id}", UserDTO.class,
                    id);
        } catch (HttpStatusCodeException e) {
            throw handleException(e);
        }
    }

    /**
     * ?HystrixBadRequestException?
     */
    protected Exception handleException(HttpStatusCodeException e) {
        HttpStatus status = e.getStatusCode();
        if (status.equals(HttpStatus.BAD_REQUEST)) {
            throw new HystrixBadRequestException(e.getResponseBodyAsString(), e);
        }
        throw e;
    }
}