核心功能 Feign + Hystrix 服务熔断和服务降级

服务降级即指 返回默认值
服务熔断即指 服务不可用或请求服务超时 即调用服务降级

1springcloud消费者(consumer)引入 Feign依赖,会自动引入Hystrix依赖的

<!-- Feign模块,接着引入相关依赖,引入Feign依赖,会自动引入Hystrix依赖的 -->
 <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

2新建FeignService类

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.*;

import com.jorian.sc_eureka_consumer.dao.impl.FeignFallBack;

/**
 * 
 * @author gyn
 *
 */
//value=“你用到的服务名称”
//fallback = FeignService实现类 我们这里先创建接口 下一步在创建FeignFallBack
@FeignClient(value = "provider-user",fallback = FeignFallBack.class)

public interface FeignService {
	//服务中方法的映射路径
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    String hello(@RequestParam("name") String name);

}

3FeignService实现类 ,配置服务不可调用时返回值

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jorian.sc_eureka_consumer.dao.FeignService;

/**
 * 
 * @author gyn
 * 配置服务不可调用时返回值
 */
@Component
@RequestMapping("/")//配置路径
public class FeignFallBack implements FeignService{
    //实现的方法是服务调用的降级方法
    @Override
    public String hello(String name) {
        return "hello error";
    }

  
}

4 application.yml后面加入

feign:
  hystrix:
    enabled: true
    
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 2000

timeoutInMilliseconds调用生产者的超时时间 默认1秒 不配置抛异常 具体几秒根据自己需要来配置

5

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.jorian.sc_eureka_consumer.dao.FeignService;

 
@RestController
public class HelloController {
	@Autowired
	private RestTemplate resttemplate;
	@Autowired
    FeignService feignService;

	@RequestMapping("/consumer")
	public String consumer(String name){
		System.err.println("---------------   login hello "+name);
		//返回值类型和我们的业务返回值一致
		return feignService.hello(name);
	
	}
}

6关闭所有生产者(provider)
调用 http://localhost:7902/consumer?name=qwer
springcloud集成Feign,Hystrix_降级服务
如图所示即配成功