核心功能 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
如圖所示即配成功