SpringBoot中Hystrix使用

1)添加pom依赖
<!-- 配合hystrix对服务请求进行实时监控:实施累加记录所有关于hystrixCommand的执行信息 -->
           <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
           </dependency>
<!-- 路由断路隔离,对HystrixCommand执行信息进行实时累加需要star中添加@EnableCircuitBreaker,Controller中添加@HystrixCommand(fallbackMethod = "熔断方法") -->
           <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
        </dependency>
 
2)容错处理
    启动类添加@EnableHystrix注解
 
package com.threepicture;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
importorg.springframework.cloud.netflix.eureka.EnableEurekaClient;
importorg.springframework.cloud.netflix.feign.EnableFeignClients;
importorg.springframework.cloud.netflix.hystrix.EnableHystrix;
/**
 * 启动加载,必须放在项目根目录
 * @author 杏仁拌饭
 *
 */
@SpringBootApplication
//eureka客户端注册(此注解属于组合注解包含@EnableDiscoveryClient)
@EnableEurekaClient
//开启hystrix断路功能-需要在contrller中配置HystrixCommand;@EnableHystrix封装了@EnableCircuitBreaker
@EnableHystrix
//Feign负载
@EnableFeignClients
//定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中
//@ComponentScan( basePackages = "com.threepicture.frame.*")
//将项目中对应的mapper类的路径加进来就可以了
@MapperScan("com.threepicture.dao.mapper")
public class StartApplication {
     private static Logger logger = LoggerFactory.getLogger(StartApplication.class);
     
     public static void main(String[] args) {
           
           logger.info("进入cust....");
           
           SpringApplication.run(StartApplication.class, args);
     }
}

  

    2.1)简单配置
        2.1.1)Controller配置@HystrixCommand注解
 
package com.threepicture.controller;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.threepicture.server.impl.ProductService;
 
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
 
@RestController
@RequestMapping("/query-cust")
public class ProductController {
    
    private Logger logger = LoggerFactory.getLogger(ProductController.class);
    
    //注入服务
    @Autowired
    private ProductService productService;
    
    @Autowired
    private ProductFeignClient productFeignClient;
    
    @RequestMapping("/test")
    @HystrixCommand(fallbackMethod = "fallBackInfo")
    public String getException() throws Exception{
        throw new Exception("测试hystrix断路功能...");
    }
    
    public String fallBackInfo(){
        return "服务暂时不可用,请稍后再试";
    }
 
}

  

简单配置至此完成使用http://localhost:18702/query-cust/test测试返回“服务暂时不可用,请稍后再试”
 
2.2)配合Feign使用熔断或者降级
    2.2.1)配置文件application.properties
 
#feign开启熔断
feign.hystrix.enable=true
 
#feign使用ribbon所以使用feign时候需要配置ribbon
#读取时间-请求处理超时时间
ribbon.ReadTimeout=60000
#链接时间-请求链接超时时间
ribbon.ConnectTimeout=60000
#开启ribbon使用eureka注册表功能
ribbon.eureka.enable=true
#熔断器超时时间开启
hystrix.command.default.excution.timeout.enable=true
#熔断超时时间
hystrix.command.default.excution.isolation.thread.timeoutInMilliseconds=120000

  

    2.2.2)feign调用接口@FeignClient注解添加fallbackFactory属性
package com.threepicture.feignClient;
 
import java.util.Map;
 
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
 
/**
* 请求产品工程客户端
* @author 杏仁拌饭
*
*/
//fallbackFactory-为feign定义检查回退
@FeignClient(name="tp-cust", fallbackFactory=ProductFeignClientFallback.class)
public interface ProductFeignClient {
    
    /**
     * 使用post方式调用带参构造方法
     * @param requestMap
     * @param id
     * @return
     */
    @RequestMapping(value="/query-product/ProductInfoById", method=RequestMethod.POST)
    public Object getProductInfoById(@RequestBody Map<String, Object> requestMap, @RequestParam("id") String id);
    
    /**
     * 使用get方式调用方法
     * @return
     */
    @RequestMapping(value="query-product/queryAllInfo", method=RequestMethod.GET)
    public Object getproductAllInfo();
    
}
 
2.2.3)添加熔断处理类
 
package com.threepicture.feignClient;
 
import java.util.HashMap;
import java.util.Map;
 
import org.springframework.stereotype.Component;
 
import com.threepicture.util.ProductConstants;
 
import feign.hystrix.FallbackFactory;
 
@Component
public class ProductFeignClientFallback implements FallbackFactory<ProductFeignClient> {
 
    @Override
    public ProductFeignClient create(Throwable cause) {
        
        return new ProductFeignClient() {
            
            @Override
            public Object getproductAllInfo() {
                
                Map<String, Object> responseMap = new HashMap<String, Object>();
                
                responseMap.put(ProductConstants.OPT_ID, "/query-product/ProductInfoById");
                
                return fallback(responseMap);
                
            }
            
            @Override
            public Object getProductInfoById(Map<String, Object> requestMap, String id) {
                
                Map<String, Object> responseMap = new HashMap<String, Object>();
                
                responseMap.put(ProductConstants.OPT_ID, "query-product/queryAllInfo");
                
                return fallback(responseMap);
                
            }
            
            public Object fallback(Map<String, Object> responseMap){
                
//                Optional<T>
                
                responseMap.put(ProductConstants.RESPONSE_MSSAGE_KEY, ProductConstants.RESPONSE_ERROR_MESSAGE_INFO_OF_HYSTRIX);
                
                responseMap.put(ProductConstants.RESPONSE_TYPE, ProductConstants.RESPONSE_TYPE_E);
                
                return responseMap;
                
            }
        };
        
    }
    
}

  

注意:@HystrixCommand-熔断机制注解;@@EnableCircuitBreaker和@EnableHystrix注解作用一致,只是@EnableHystrix封装了@EnableCircuitBreaker注解;@EnableHystrixDashboard是对微服务监控的可视化界面展示
posted @ 2019-03-24 19:43  杏仁拌饭  阅读(869)  评论(0)    收藏  举报