SpringCloud:Hystrix熔断器
JAVA烂猪皮
共 6699字,需浏览 14分钟
·
2023-08-01 09:55
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
@EnableDiscoveryClient
@SpringBootApplication
@EnableHystrix
public class ConsumerDeptRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerDeptRibbonApplication.class, args);
}
}
@Service
public class DeptService {
@Autowired
private RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "hiError")
public String sayHi(String message) {
//这里指指定了服务名称,不用管ip 地址与端口
return restTemplate.getForObject("http://SPRING-CLOUD-LEARN-PROVIDER-DEPT/hi?message=" + message, String.class);
}
public String hiError(String message) {
return "Hi,your message is :\"" + message + "\" but request error.";
}
}
feign:
hystrix:
enabled: true
@Component
public class DeptServiceHystrix implements DeptService {
@Override
public String sayHi(String message) {
return "Hi,your message is :\"" + message + "\" but request error.";
}
}
//服务提供者的名字
@FeignClient(value = "spring-cloud-learn-provider-dept", fallback = DeptServiceHystrix.class)
public interface DeptService {
@RequestMapping(value = "hi", method = RequestMethod.GET)
String sayHi(@RequestParam(value = "message") String message);
}
@Component
public class DeptServiceFallbackFactory implements FallbackFactory<DeptService> {
@Override
public DeptService create(Throwable throwable) {
return new DeptService() {
@Override
public String sayHi(String message) {
return "Hi,your message is :\"" + message + "\" but request error.";
}
};
}
}
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableHystrixDashboard
public class ConsumerDeptFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerDeptFeignApplication.class, args);
}
}
@Configuration
public class HystrixDashboardConfiguration {
@Bean
public ServletRegistrationBean getServlet() {
HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
registrationBean.setLoadOnStartup(1);
registrationBean.addUrlMappings("/hystrix.stream");
registrationBean.setName("HystrixMetricsStreamServlet");
return registrationBean;
}
}
剩下的就不会给大家一展出来了,以上资料按照一下操作即可获得
——将文章进行转发和评论,关注公众号【Java烤猪皮】,关注后继续后台回复领取口令“ 666 ”即可免费领文章取中所提供的资料。
腾讯、阿里、滴滴后台试题汇集总结 — (含答案)
面试:史上最全多线程序面试题!
最新阿里内推Java后端试题
JVM难学?那是因为你没有真正看完整这篇文章
关注作者微信公众号 — 《JAVA烤猪皮》
了解了更多java后端架构知识以及最新面试宝典
看完本文记得给作者点赞+在看哦~~~大家的支持,是作者来源不断出文的动力~
评论