1. 程式人生 > >SpringCloud整合Hystrix斷路器和feign整合Hystrix的使用(熔斷 》降級之後的報警機制)

SpringCloud整合Hystrix斷路器和feign整合Hystrix的使用(熔斷 》降級之後的報警機制)

SpringCloud整合Hystrix斷路器

		<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
  1. 在啟動類上面填加註解 @EnableCircuitBreaker
  2. 在最外層的Api使用,也就是Controller層中需要新增斷路器的方法上,添加註解@HystrixCommand(fallbackMethod = “abc(方法名)”), 編寫abc方法的具體實現,方法的引數必須和加@HystrixCommand註解的方法的引數一樣。其實就好比異常處理,如果加@HystrixCommand註解的方法中出現異常,會走註解中命名的方法。
@RestController
@RequestMapping("api/v1/order")
public class OrderController {
//這個是service層
    @Autowired
    private ProductOrderService productOrderService;

    @RequestMapping("save")
    @HystrixCommand(fallbackMethod = "abc")
    public Object save(@RequestParam("user_id")int userId, 
    					@RequestParam("product_id") int productId){

        Map<String, Object> data = new HashMap<>();
        data.put("code", 0);
        data.put("data", productOrderService.save(userId, productId));
        return  data;
    }


    //注意,方法中的引數一定要和api方法的一致
    private Object abc(int userId, int productId){

        Map<String, Object> msg = new HashMap<>();
        msg.put("code", -1);
        msg.put("msg", "搶購人數太多,您被擠出來了,稍等重試");
        return msg;
    }
    
}

feign結合Hystrix的使用

  1. 開啟feign支援hystrix (舊版本預設支援,新版本預設關閉),設定Hystrix的超時時間預設是1秒
#開啟feign支援hystrix
feign:
	hystrix:
		 enabled: true
#設定hystrix的超時時間 預設是1000毫秒		 
hystrix:
	  command:
	    default:
	      execution:
	        isolation:
	          thread:
	            timeoutInMilliseconds: 2000				  
  1. 自定義一個類,去實現添加了@FeignClient(name = “product-service(服務名)”, fallback = xxx.class)註解的介面。xxx是實現了該介面的類名。 自定義的類必須要新增到spring容器中所以一定要新增@Component註解
/**
 * 商品服務客戶端
 */
@FeignClient(name = "product-service", fallback = ProductClientFallback.class)
public interface ProductClient {    
    @GetMapping("/api/v1/product/find")
    String findById(@RequestParam(value = "id") int id);   
}
=====================================================================

/**
 * 針對商品服務,錯降級處理
 */
@Component
public class ProductClientFallback implements ProductClient {
    @Override
    public String findById(int id) {
        System.out.println("feign 呼叫product-service findbyid 異常");
        return null;
    }
}

熔斷降級服務異常報警通知

  1. 加入redis依賴
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
  1. 在application.yml的配置檔案中配置redis
spring:
  redis:
    database: 0  # Redis資料庫索引(預設為0)
    host: 127.0.0.1 #Redis伺服器地址
    port: 6379   # Redis伺服器連線埠
    timeout: 2000  # 連線超時時間(毫秒)
    //注意,方法簽名一定要要和api方法一致
    private Object saveOrderFail(int userId, int productId){

        //監控報警
        String saveOrderKye = "save-order";
        //從redis資料庫取資料來判斷是否傳送傳送過簡訊
        String sendValue = redisTemplate.opsForValue().get(saveOrderKye);
        //新建一個執行緒去執行
        new Thread( ()->{
        //判斷是否傳送過簡訊,sendValue如果取出來的是null,就說明沒有傳送過簡訊
            if (StringUtils.isBlank(sendValue)) {
                System.out.println("緊急簡訊,使用者下單失敗,請離開查詢原因);
                //傳送一個http請求,呼叫簡訊服務 TODO

				//傳送過簡訊後就隨便儲存一個值,設定過期時長
                redisTemplate.opsForValue().set(saveOrderKye, "save-order-fail", 20, TimeUnit.SECONDS);

            }else{
                System.out.println("已經發送過簡訊,20秒內不重複傳送");
            }

        }).start();


        Map<String, Object> msg = new HashMap<>();
        msg.put("code", -1);
        msg.put("msg", "搶購人數太多,您被擠出來了,稍等重試");
        return msg;
    }

熔斷和降級互相交集 相同點: 1. 從可用性和可靠性觸發,為了防止系統崩潰 2. 最終讓使用者體驗到的是某些功能暫時不能用 不同點: 1. 熔斷一般是下游服務故障導致的,而服務降級一般是從整體系統負荷考慮,由呼叫方控制