(六十九)java版spring cloud微服務架構b2b2c電子商務平臺--Hystrix 基本配置

1、 【microcloud-provider-dept-hystrix-8001】修改 pom.xml 配置文件,追加 Hystrix 配置類:

       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-hystrix</artifactId>
       </dependency>

2、 【microcloud-provider-dept-hystrix-8001】修改 DeptRest 程序

package cn.study.microcloud.rest;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import cn.study.microcloud.service.IDeptService;
import cn.study.vo.Dept;

@RestController
public class DeptRest {
    @Resource
    private IDeptService deptService;
    @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
    @HystrixCommand(fallbackMethod="getFallback")    // 如果當前調用的get()方法出現了錯誤,則執行fallback
    public Object get(@PathVariable("id") long id) {
        Dept vo = this.deptService.get(id) ;    // 接收數據庫的查詢結果
        if (vo == null) {    // 數據不存在,假設讓它拋出個錯誤
            throw new RuntimeException("部門信息不存在!") ;
        }
        return vo ;
    }
    public Object getFallback(@PathVariable("id") long id) {    // 此時方法的參數 與get()一致
        Dept vo = new Dept() ;
        vo.setDeptno(999999L);
        vo.setDname("【ERROR】Microcloud-Dept-Hystrix");    // 錯誤的提示
        vo.setLoc("DEPT-Provider");
        return vo ;
    }
    
    
}

一旦 get()方法上拋出了錯誤的信息,那麼就認爲該服務有問題,會默認使用“@HystrixCommand”註解之中配置好的 fallbackMethod 調用類中的指定方法,返回相應數據。

3、 【microcloud-provider-dept-hystrix-8001】在主類之中啓動熔斷處理

package cn.study.microcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker
@EnableDiscoveryClient
public class Dept_8001_StartSpringCloudApplication {
    public static void main(String[] args) {
        SpringApplication.run(Dept_8001_StartSpringCloudApplication.class, args);
    }
}

現在的處理情況是:服務器出現了錯誤(但並不表示提供方關閉),那麼此時會調用指定方法的 fallback 處理。

發佈了101 篇原創文章 · 獲贊 118 · 訪問量 7522
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章