1. 程式人生 > >SpringCloud與idea在專案中相遇:第五天,Hystrix

SpringCloud與idea在專案中相遇:第五天,Hystrix

  1. 服務熔斷

a)以vlluviaCloud-provider-dept-8001為原型建立vlluviaCloud-provider-dept-hystrix-8001 專案

在這裡插入圖片描述

b)修改PersonController 類

@RequestMapping(value = "/person/get/{id}", method = RequestMethod.GET)
@HystrixCommand(fallbackMethod = "processHystrix_Get")
public Person getPerson(@PathVariable("id") int id) {
    
    if (id == 0)
        throw new RuntimeException("該ID:" + id + "沒有沒有對應的資訊");

    for (Person person : get()) {
        if (person.getId() == id)
            return person;
    }
    return null;
}
public Person processHystrix_Get(@PathVariable("id")int id)
{
    return new Person(id,"該ID:" + id + "沒有沒有對應的資訊,
[email protected]
","no this database in MySQL"); }

c)修改HystrixApplication 類

在這裡插入圖片描述

d)修改vlluviaCloud-api 專案

e)新增DeptClientServiceFallbackFactory 類

@Component // 不要忘記新增,不要忘記新增
public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService>
{
   @Override
   public DeptClientService create(Throwable throwable)
   {
      return new DeptClientService() {
         @Override
         public Person get(long id)
         {
            return new Person(Math.toIntExact(id),"該ID:" + id + "沒有沒有對應的資訊,
[email protected]
","no this database in MySQL"); } @Override public List<Person> gets() { return null; } }; } }

f)修改DeptClientService類

在這裡插入圖片描述

g)修改vlluviaCloud-consumer-dept-feign專案

h)修改application.yml

server:
  port: 80


feign:
  hystrix:
    enabled: true

spring:
  application:
    name: consumer-dept-80

eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka1:7001/eureka/,http://eureka2:7002/eureka/,http://eureka3:7003/eureka/

i)按順序執行

	vlluviaCloud-eureka-7001
	vlluviaCloud-provider-dept-hystrix-8001
	vlluviaCloud-consumer-dept-feign

訪問http://localhost/consumer/person/gets 在這裡插入圖片描述

在這裡插入圖片描述

  1. 服務降級

a)建立專案vlluviaCloud-consumer-hystrix-dashboard 在這裡插入圖片描述

b)修改application.yml

server:
  port: 9001

c)修改HystrixDashboardApplication 在這裡插入圖片描述