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; } }
正常请求:
停用服务提供者:
下一篇:
看一看Java架构师需要具备的3种能力!