SpringCloud Feign Hystrix后備

2023-11-24 14:28 更新

Hystrix支持回退的概念:當(dāng)它們的電路斷開(kāi)或出現(xiàn)錯(cuò)誤時(shí)執(zhí)行的默認(rèn)代碼路徑。要為給定的@FeignClient啟用回退,請(qǐng)將fallback屬性設(shè)置為實(shí)現(xiàn)回退的類名稱。您還需要將實(shí)現(xiàn)聲明為Spring bean。

@FeignClient(name = "hello", fallback = HystrixClientFallback.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

static class HystrixClientFallback implements HystrixClient {
    @Override
    public Hello iFailSometimes() {
        return new Hello("fallback");
    }
}

如果需要訪問(wèn)引起后備觸發(fā)器的原因,則可以使用@FeignClient中的fallbackFactory屬性。

@FeignClient(name = "hello", fallbackFactory = HystrixClientFallbackFactory.class)
protected interface HystrixClient {
	@RequestMapping(method = RequestMethod.GET, value = "/hello")
	Hello iFailSometimes();
}

@Component
static class HystrixClientFallbackFactory implements FallbackFactory<HystrixClient> {
	@Override
	public HystrixClient create(Throwable cause) {
		return new HystrixClient() {
			@Override
			public Hello iFailSometimes() {
				return new Hello("fallback; reason was: " + cause.getMessage());
			}
		};
	}
}
Feign中的后備實(shí)現(xiàn)以及Hystrix后備如何工作存在局限性。返回com.netflix.hystrix.HystrixCommandrx.Observable的方法當(dāng)前不支持后備。
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)