我有服務在應用程序啓動後運行一些init腳本(使用ApplicationListener<ApplicationReadyEvent>
實現)。在這個腳本中,我需要調用RestTemplate
的另一個服務,它是@LoadBalanced
。當調用服務調用時,沒有關於遠程服務實例的信息,因爲當時沒有聯繫發現服務器(我猜)。負載均衡功能區客戶端初始化發現服務(尤里卡)
java.lang.IllegalStateException: No instances available for api-service
at org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.execute(RibbonLoadBalancerClient.java:79)
那麼,有沒有辦法如何在應用程序啓動時得到發現服務器提供的服務的列表中,在我的init腳本將執行?
感謝
編輯: 問題是更相關的事實,在當前的環境(DEV)的所有服務捆綁在一起的一個服務(API服務)。所以從api服務中,我試圖調用@LoadBalanced客戶端API服務,它不知道自己?我可以註冊一些聽衆或類似的東西,知道何時可以使用api-service(self)?
here是示例應用程序。我主要想如何讓工作this method
EDIT2:
現在有可能創造EurekaListener
public static class InitializerListener implements EurekaEventListener {
private EurekaClient eurekaClient;
private RestOperations restTemplate;
public InitializerListener(EurekaClient eurekaClient, RestOperations restTemplate) {
this.eurekaClient = eurekaClient;
this.restTemplate = restTemplate;
}
@Override
public void onEvent(EurekaEvent event) {
if (event instanceof StatusChangeEvent) {
if (((StatusChangeEvent) event).getStatus().equals(InstanceInfo.InstanceStatus.UP)) {
ResponseEntity<String> helloResponse = restTemplate.getForEntity("http://api-service/hello-controller/{name}", String.class, "my friend");
logger.debug("Response from controller is {}", helloResponse.getBody());
eurekaClient.unregisterEventListener(this);
}
}
}
}
,然後像這樣註冊它的解決方案:
EurekaEventListener initializerListener = new InitializerListener(discoveryClient, restTemplate);
discoveryClient.registerEventListener(initializerListener);
但是,這隻有在應用程序第一次註冊到發現服務時才執行。下一次當我停止api服務並再次運行時,事件不會發布。有沒有其他的事件可以抓到?
即使當我將事件更改爲InstanceRegisteredEvent時,我也得到相同的異常(沒有可用的實例 - 我將它推送到github)。有什麼可以幫助我嗎?我可以看到來自事件的配置對象可以轉換爲'EurekaInstanceConfigBean',從那裏我可以獲得目標服務的IP地址和端口,但我認爲在這種情況下我不能使用@LoadBalanced rest模板。如果我能以某種方式幫助你調查這個問題,請告訴我。我需要在當前進程中具有此功能。謝謝 – bilak
我已經創建了監聽器(請參閱已編輯的問題),但存在的問題是每次重新啓動應用程序時都不會執行它。 – bilak
是否可以偵聽每次應用程序註冊到註冊表服務器時調用的某個事件? – bilak