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

正常请求:

停用服务提供者:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值