java B2B2C springmvc mybatis電子商務平臺源碼-Hystrix 基本配置

一、 【microcloud-provider-dept-hystrix-8001】修改 pom.xml 配置文件,追加 Hystrix 配置類:須要JAVA Spring Cloud大型企業分佈式微服務雲構建的B2B2C電子商務平臺源碼一零三八七七四六二六java

<dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-hystrix</artifactId>
       </dependency>
複製代碼

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

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 調用類中的指定方法,返回相應數據。spring

三、 【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 處理。java B2B2C springmvc mybatis電子商務平臺源碼bash

相關文章
相關標籤/搜索