天天看點

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

springcloud內建Feign,Hystrix

如圖所示即配成功

繼續閱讀