网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

详解springcloud使用Hystrix实现单个方法的fallback

本文介绍了spring cloud-使用Hystrix实现单个方法的fallback,分享给大家,具体如下:

专注于为中小企业提供网站设计制作、成都网站制作服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业赫章免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上千多家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

一、加入Hystrix依赖

 
      org.springframework.cloud 
      spring-cloud-starter-hystrix 
     

二、编写Controller

package com.chhliu.springboot.restful.controller;  
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RestController;  
import com.chhliu.springboot.restful.feignclient.UserFeignClient; 
import com.chhliu.springboot.restful.vo.User; 
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;  
@RestController 
public class RestTemplateControllerHystrixCommand { 
   
  @Autowired 
  private UserFeignClient client; // 使用Feign来消费Restful服务 
   
  @GetMapping("/get/{id}") 
  @HystrixCommand(fallbackMethod="findByIdFallback")// 使用HystrixCommand注解,在fallbackMethod属性中指定fallback的方法 
  public User findById(@PathVariable Long id) { 
    return client.findById(id); 
  } 
   
    // 覆写fallbackMethod中指定的方法,注意,此方法的返回值,参数必须与原方法一致 
  public User findByIdFallback(Long id){ 
    User u = new User(); 
    u.setName("zhangsan"); 
    u.setUsername("chhliu"); 
    u.setId(9L); 
    return u; 
  } 
} 

三、在启动类中添加Hystrix支持

@EnableCircuitBreaker 

四、添加配置文件

server.port:7904 
# spring boot服务注册到Eureka Server上的应用名称 
spring.application.name=springboot-rest-template-feign-hystrix 
eureka.instance.prefer-ip-address=true 
# Eureka Server注册服务的地址 
eureka.client.service-url.defaultZone=http://chhliu:chhliu123456@localhost:8764/eureka 
springboot-h3.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RetryRule 
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 1 #为了测试Hystrix的fallback效果,此处将超时时间设置成1毫秒 

五、测试

在浏览器中输入:http://localhost:7904/get/2

测试结果如下:

{"id":9,"username":"chhliu","name":"zhangsan","age":null,"balance":null} 

从上面的测试结果可以看出,由于连接超时,直接进入了fallback方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


网页题目:详解springcloud使用Hystrix实现单个方法的fallback
新闻来源:http://bjjierui.cn/article/pijggd.html

其他资讯