springcloud之Hystrix初識篇—結合ResTeamplate使用簡例

1、添加pom依賴。

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
   <version>2.2.1.RELEASE</version>
</dependency>

2、coding

啓動項添加配置

@SpringBootApplication
@EnableHystrix
public class TestDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestDemoApplication.class, args);
    }
}

編寫service實例

public interface HystrixRestTemplateService {

    String hystrixRestTemplateSend(String body);
}
import com.example.springcloud.testdemo.exception.HystrixIgnoreException;
import com.example.springcloud.testdemo.service.HystrixRestTemplateService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * Created by py
 * 2020/3/24
 */
@Service
public class HystrixRestTemplateServiceImpl implements HystrixRestTemplateService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Override
    //fallbackMethod:請求異常執行備用邏輯(降級)的方法名稱
    @HystrixCommand(fallbackMethod="sendFail")
    public String hystrixRestTemplateSend(String body) {
        String url = "http://test1/eureka-clinet1/hystrixRestTemplate/Code";
        ResponseEntity<String> result = restTemplate.postForEntity(url,body,String.class);
        return "test";
    }
    /**
     *  降級方法:調用方法異常則執行此方法
     *  PS:請求參數和返回類型要和使用該降級方法的方法保持一致
     */
    public String sendFail(String body){
        /*備用邏輯:
          body :hystrixRestTemplateSend方法請求的參數  
          這塊我們可以組裝參數告知客戶端異常,或基於自己業務需求做其他處理
        */
        return "restTemplate熔斷:"+body;
    }
}

創建controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by py
 * 2020/3/24
 */
@RestController
public class HystrixTestController {

    @Autowired
    private HystrixRestTemplateService hystrixRestTemplateService;

    @PostMapping("/hystrixRestTemplate/Send")
    public String hystrixSend(@RequestBody String body){

        String result = hystrixRestTemplateService.hystrixRestTemplateSend(body);

        return result;
    }
}

正常請求:

停用服務提供者:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章