原创

9.Springcloud的Hystrix服务熔断和服务降级

项目地址:

github地址

服务熔断和服务降级异同

相同点:让用户体验到的是某些功能暂时不可用;都是从可用性和可靠性出发,为了防止系统崩溃;
不同点:
服务熔断:一般是某个服务(下游服务)故障引起,
服务降级:一般是从整体负荷考虑;

服务熔断的实现方式

1.在服务端添加hystrix坐标

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

2.在对应需要熔断的接口的地方添加注解并编写熔断错误提示的代码

具体的注解是:@HystrixCommand(fallbackMethod = "processHystrix_Get"),其中的fallbackMethod是一旦服务抛出异常之后,会对该参数指定的方法进行调用返回
示例代码:

package com.debuggg.cloud.controller;

import com.debuggg.cloud.entities.Dept;
import com.debuggg.cloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeptController {
    @Autowired
    private DeptService deptService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/dept/list",method = RequestMethod.GET)
    public List<Dept> list(){
        return deptService.list();
    }

    @RequestMapping(value = "/dept/get/{id}",method = RequestMethod.GET)
    @HystrixCommand(fallbackMethod = "processHystrix_Get")
    public Dept get(@PathVariable("id") Long id){
        Dept dept = deptService.get(id);
        if(dept == null){
            throw new RuntimeException("不能为空!");
        }else{
            return dept;
        }
    }

    @RequestMapping(value = "/dept/add",method = RequestMethod.POST)
    public Boolean add(@RequestBody Dept dept){
        return deptService.add(dept);
    }

    @RequestMapping(value = "/dept/discovery", method = RequestMethod.GET)
    public Object discovery()
    {
        List<String> list = discoveryClient.getServices();
        System.out.println("**********" + list);

        List<ServiceInstance> srvList = discoveryClient.getInstances("DEBUGGGCLOUD-DEPT");
        for (ServiceInstance element : srvList) {
            System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
                    + element.getUri());
        }
        return this.discoveryClient;
    }

    public Dept processHystrix_Get(@PathVariable("id") Long id)
    {
        return new Dept().setDeptno(id)
                .setDname("该ID:"+id+"没有没有对应的信息,null--@HystrixCommand")
                .setDb_source("no this database in MySQL");
    }
}

服务降级的实现方式

服务降级:服务降级处理时在客户端实现完成的,与服务端没有关系

1.修改microservicecloud-api工程,根据已经有的DeptClientService接口新建一个实现了FallbackFactory接口的类DeptClientServiceFallbackFactory,千万不要忘记在类上面新增@Component注解,大坑!!!

示例代码:

package com.debuggg.cloud.service;

import com.debuggg.cloud.entities.Dept;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DeptClientServiceFallback implements FallbackFactory<DeptClientService> {
    @Override
    public DeptClientService create(Throwable throwable) {
        return new DeptClientService() {
            @Override
            public Dept get(long id) {
                return new Dept().setDeptno(id)
                        .setDname("该ID:"+id+"没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭")
                        .setDb_source("no this database in MySQL");
            }

            @Override
            public List<Dept> list() {
                return null;
            }

            @Override
            public boolean add(Dept dept) {
                return false;
            }
        };
    }
}

2.修改microservicecloud-api工程,DeptClientService接口在注解@FeignClient中添加fallbackFactory属性值

@FeignClient(value = "DEBUGGGCLOUD-DEPT",fallbackFactory = DeptClientServiceFallback.class)

3.修改yml

server:
  port: 10001
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
    register-with-eureka: false
**
feign:
  hystrix:
    enabled: true #启用服务降级**
正文到此结束
本文目录