springcloud集成Feign,Hystrix

核心功能 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
在这里插入图片描述
如图所示即配成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值