com.netflix.discovery.CacheRefreshedEvent Java Examples

The following examples show how to use com.netflix.discovery.CacheRefreshedEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DiscoveryClientConfig.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Bean(destroyMethod = "shutdown")
@RefreshScope
public ApimlDiscoveryClient eurekaClient(ApplicationInfoManager manager,
                                         EurekaClientConfig config,
                                         EurekaInstanceConfig instance,
                                         @Autowired(required = false) HealthCheckHandler healthCheckHandler
) {
    ApplicationInfoManager appManager;
    if (AopUtils.isAopProxy(manager)) {
        appManager = ProxyUtils.getTargetObject(manager);
    } else {
        appManager = manager;
    }
    final ApimlDiscoveryClient discoveryClientClient = new ApimlDiscoveryClient(appManager, config, this.optionalArgs, this.context);
    discoveryClientClient.registerHealthCheck(healthCheckHandler);

    discoveryClientClient.registerEventListener(event -> {
        if (event instanceof CacheRefreshedEvent) {
            refreshableRouteLocators.forEach(RefreshableRouteLocator::refresh);
            zuulHandlerMapping.setDirty(true);
        }
    });
    return discoveryClientClient;
}
 
Example #2
Source File: DiscoveryClientTestConfig.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Bean(destroyMethod = "shutdown")
@RefreshScope
public ApimlDiscoveryClientStub eurekaClient(ApplicationInfoManager manager,
                                             EurekaClientConfig config,
                                             EurekaInstanceConfig instance,
                                             @Autowired(required = false) HealthCheckHandler healthCheckHandler,
                                             ApplicationRegistry applicationRegistry
) {
    ApplicationInfoManager appManager;
    if (AopUtils.isAopProxy(manager)) {
        appManager = ProxyUtils.getTargetObject(manager);
    } else {
        appManager = manager;
    }

    final ApimlDiscoveryClientStub discoveryClient = new ApimlDiscoveryClientStub(appManager, config, this.optionalArgs, this.context, applicationRegistry);
    discoveryClient.registerHealthCheck(healthCheckHandler);

    discoveryClient.registerEventListener(event -> {
        if (event instanceof CacheRefreshedEvent) {
            refreshableRouteLocators.forEach(RefreshableRouteLocator::refresh);
            zuulHandlerMapping.setDirty(true);
        }
    });
    return discoveryClient;
}
 
Example #3
Source File: ServiceCacheEvictorTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
void testService() {
    serviceCacheEvictor.onEvent(mock(CacheRefreshedEvent.class));
    verify(apimlLoadBalancer1, never()).updateListOfServers();

    serviceCacheEvictor.evictCacheService("service1");
    serviceCacheEvictor.evictCacheService("service2");
    serviceCacheEvictor.onEvent(mock(CacheRefreshedEvent.class));
    serviceCacheEvicts.forEach(x -> {
        verify(x, times(1)).evictCacheService("service1");
        verify(x, times(1)).evictCacheService("service2");
    });
    verify(apimlLoadBalancer1, times(1)).updateListOfServers();

    serviceCacheEvictor.evictCacheService("service3");
    serviceCacheEvictor.evictCacheAllService();
    serviceCacheEvictor.evictCacheService("service4");
    serviceCacheEvictor.onEvent(mock(CacheRefreshedEvent.class));
    serviceCacheEvicts.forEach(x -> {
        verify(x, never()).evictCacheService("service3");
        verify(x, times(1)).evictCacheAllService();
    });
    verify(apimlLoadBalancer3, times(3)).updateListOfServers();
}
 
Example #4
Source File: EurekaDynamicServerListLoadBalancerTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadBalancerHappyCase() throws Exception {
    Assert.assertNotEquals("the two test server list counts should be different",
            secondServerListSize, initialServerListSize);

    DynamicServerListLoadBalancer<DiscoveryEnabledServer> lb = null;
    try {
        Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>();
        eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture));

        PowerMock.replay(DiscoveryClient.class);
        PowerMock.replay(eurekaClientMock);

        // actual testing
        // initial creation and loading of the first serverlist
        lb = new DynamicServerListLoadBalancer<DiscoveryEnabledServer>(
                config,
                new AvailabilityFilteringRule(),
                new DummyPing(),
                new DiscoveryEnabledNIWSServerList(vipAddress, eurekaClientProvider),
                new ZoneAffinityServerListFilter<DiscoveryEnabledServer>(),
                new EurekaNotificationServerListUpdater(eurekaClientProvider)
        );

        Assert.assertEquals(initialServerListSize, lb.getServerCount(false));

        // trigger an eureka CacheRefreshEvent
        eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent());

        Assert.assertTrue(verifyFinalServerListCount(secondServerListSize, lb));

    } finally {
        if (lb != null) {
            lb.shutdown();

            PowerMock.verify(eurekaClientMock);
            PowerMock.verify(DiscoveryClient.class);
        }
    }
}
 
Example #5
Source File: EurekaNotificationServerListUpdaterTest.java    From ribbon with Apache License 2.0 5 votes vote down vote up
@Test
public void testEurekaClientUnregister() {
    ThreadPoolExecutor executorMock = EasyMock.createMock(ThreadPoolExecutor.class);
    EasyMock.expect(executorMock.isShutdown()).andReturn(Boolean.TRUE);

    EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater(
            new Provider<EurekaClient>() {
                @Override
                public EurekaClient get() {
                    return eurekaClientMock;
                }
            },
            executorMock
    );

    try {
        Capture<EurekaEventListener> registeredListener = new Capture<EurekaEventListener>();
        eurekaClientMock.registerEventListener(EasyMock.capture(registeredListener));

        EasyMock.replay(eurekaClientMock);
        EasyMock.replay(executorMock);

        serverListUpdater.start(new ServerListUpdater.UpdateAction() {
            @Override
            public void doUpdate() {
                Assert.fail("should not reach here");
            }
        });

        registeredListener.getValue().onEvent(new CacheRefreshedEvent());
        
    } finally {
        EasyMock.verify(executorMock);
        EasyMock.verify(eurekaClientMock);
    }

}
 
Example #6
Source File: ServiceCacheEvictor.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public synchronized void onEvent(EurekaEvent event) {
    if (event instanceof CacheRefreshedEvent) {
        if (!evictAll && toEvict.isEmpty()) return;
        if (evictAll) {
            serviceCacheEvicts.forEach(ServiceCacheEvict::evictCacheAllService);
            loadBalancerRegistry.values().forEach(DynamicServerListLoadBalancer::updateListOfServers);
            evictAll = false;
        } else {
            toEvict.forEach(ServiceRef::evict);
            toEvict.clear();
        }
        loadBalancerRegistry.values().forEach(DynamicServerListLoadBalancer::updateListOfServers);
    }
}
 
Example #7
Source File: EurekaContainerHealthService.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private Flux<ContainerHealthEvent> handleEurekaEvent(EurekaEvent event, ConcurrentMap<String, ContainerHealthEvent> state) {
    if (!(event instanceof CacheRefreshedEvent)) {
        return Flux.empty();
    }

    List<Pair<Job, List<Task>>> allJobsAndTasks = jobOperations.getJobsAndTasks();
    List<Task> allTasks = new ArrayList<>();
    List<ContainerHealthEvent> events = new ArrayList<>();

    allJobsAndTasks.forEach(jobAndTasks -> {
        jobAndTasks.getRight().forEach(task -> {
            handleTaskStateUpdate(jobAndTasks.getLeft(), task, state).ifPresent(events::add);
            allTasks.add(task);
        });
    });

    // Cleanup, in case we have stale entries.
    Set<String> unknownTaskIds = CollectionsExt.copyAndRemove(state.keySet(), allTasks.stream().map(Task::getId).collect(Collectors.toSet()));
    unknownTaskIds.forEach(taskId -> {
        state.remove(taskId);

        // Assume the task was terminated.
        ContainerHealthStatus terminatedStatus = ContainerHealthStatus.newBuilder()
                .withTaskId(taskId)
                .withTimestamp(titusRuntime.getClock().wallTime())
                .withState(ContainerHealthState.Terminated)
                .withReason("terminated")
                .build();

        events.add(ContainerHealthUpdateEvent.healthChanged(terminatedStatus));
    });

    return Flux.fromIterable(events);
}
 
Example #8
Source File: EurekaClientEventListener.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@Override
public void onEvent(EurekaEvent event) {
    if (event instanceof CacheRefreshedEvent) {
        publisher.publishEvent(new EurekaClientLocalCacheRefreshedEvent((CacheRefreshedEvent)event));
    } else if (event instanceof StatusChangeEvent) {
        publisher.publishEvent(new EurekaClientStatusChangeEvent((StatusChangeEvent)event));
    }
}
 
Example #9
Source File: EurekaAgentStatusMonitorTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Test
public void testTerminatedInstanceEvent() {
    ExtTestSubscriber<AgentStatus> testSubscriber = new ExtTestSubscriber<>();
    monitor.monitor().subscribe(testSubscriber);

    // Trigger instance up event.
    mockStatusInEureka(instance, InstanceStatus.UP);
    assertThat(testSubscriber.takeNext().getStatusCode()).isEqualTo(AgentStatusCode.Healthy);

    // Simulate termination of an agent instance.
    agentComponentStub.terminateInstance(agentComponentStub.getFirstInstance().getId(), true);
    monitor.onEvent(new CacheRefreshedEvent());
    assertThat(testSubscriber.takeNext().getStatusCode()).isEqualTo(AgentStatusCode.Terminated);
}
 
Example #10
Source File: EurekaAgentStatusMonitorTest.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
private void mockStatusInEureka(AgentInstance instance, InstanceStatus eurekaStatus) {
    InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder()
            .setInstanceId(instance.getId())
            .setAppName("testApp")
            .setStatus(eurekaStatus)
            .build();
    when(eurekaClient.getInstancesById(instance.getId())).thenReturn(singletonList(instanceInfo));

    monitor.onEvent(new CacheRefreshedEvent());
}
 
Example #11
Source File: SingleServiceLoadBalancer.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Override
public void onEvent(EurekaEvent event) {
    if (event instanceof CacheRefreshedEvent) {
        refresh();
    }
}
 
Example #12
Source File: EurekaNotificationServerListUpdaterTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testSubmitExceptionClearQueued() {
    ThreadPoolExecutor executorMock = EasyMock.createMock(ThreadPoolExecutor.class);
    EasyMock.expect(executorMock.submit(EasyMock.isA(Runnable.class)))
            .andThrow(new RejectedExecutionException("test exception"));
    EasyMock.expect(executorMock.isShutdown()).andReturn(Boolean.FALSE);
    EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater(
            new Provider<EurekaClient>() {
                @Override
                public EurekaClient get() {
                    return eurekaClientMock;
                }
            },
            executorMock
    );

    try {
        Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>();
        eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture));

        EasyMock.replay(eurekaClientMock);
        EasyMock.replay(executorMock);

        serverListUpdater.start(new ServerListUpdater.UpdateAction() {
            @Override
            public void doUpdate() {
                Assert.fail("should not reach here");
            }
        });

        eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent());

        Assert.assertFalse(serverListUpdater.updateQueued.get());
    } finally {
        serverListUpdater.stop();

        EasyMock.verify(executorMock);
        EasyMock.verify(eurekaClientMock);
    }

}
 
Example #13
Source File: EurekaNotificationServerListUpdaterTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testTaskAlreadyQueued() throws Exception {
    EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater(
            new Provider<EurekaClient>() {
                @Override
                public EurekaClient get() {
                    return eurekaClientMock;
                }
            },
            testExecutor
    );

    try {
        Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>();
        eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture));

        EasyMock.replay(eurekaClientMock);

        final CountDownLatch countDownLatch = new CountDownLatch(1);
        serverListUpdater.start(new ServerListUpdater.UpdateAction() {
            @Override
            public void doUpdate() {
                if (countDownLatch.getCount() == 0) {
                    Assert.fail("should only countdown once");
                }
                countDownLatch.countDown();
            }
        });

        eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent());
        eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent());

        Assert.assertTrue(countDownLatch.await(2, TimeUnit.SECONDS));
        Thread.sleep(100);  // sleep a bit more

        Assert.assertFalse(serverListUpdater.updateQueued.get());
    } finally {
        serverListUpdater.stop();

        EasyMock.verify(eurekaClientMock);
    }
}
 
Example #14
Source File: EurekaNotificationServerListUpdaterTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testStopWithCommonExecutor() throws Exception {
    EurekaNotificationServerListUpdater serverListUpdater1 = new EurekaNotificationServerListUpdater(
            new Provider<EurekaClient>() {
                @Override
                public EurekaClient get() {
                    return eurekaClientMock;
                }
            },
            testExecutor
    );

    EurekaNotificationServerListUpdater serverListUpdater2 = new EurekaNotificationServerListUpdater(
            new Provider<EurekaClient>() {
                @Override
                public EurekaClient get() {
                    return eurekaClientMock2;
                }
            },
            testExecutor
    );

    Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>();
    eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture));

    Capture<EurekaEventListener> eventListenerCapture2 = new Capture<EurekaEventListener>();
    eurekaClientMock2.registerEventListener(EasyMock.capture(eventListenerCapture2));

    EasyMock.replay(eurekaClientMock);
    EasyMock.replay(eurekaClientMock2);

    final CountDownLatch updateCountLatch = new CountDownLatch(2);
    serverListUpdater1.start(new ServerListUpdater.UpdateAction() {
        @Override
        public void doUpdate() {
            updateCountLatch.countDown();
        }
    });

    serverListUpdater2.start(new ServerListUpdater.UpdateAction() {
        @Override
        public void doUpdate() {
            updateCountLatch.countDown();
        }
    });

    eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent());
    eventListenerCapture2.getValue().onEvent(new CacheRefreshedEvent());

    Assert.assertTrue(updateCountLatch.await(2, TimeUnit.SECONDS));  // latch is for both

    serverListUpdater1.stop();
    serverListUpdater2.stop();

    EasyMock.verify(eurekaClientMock);
    EasyMock.verify(eurekaClientMock2);
}
 
Example #15
Source File: EurekaNotificationServerListUpdaterTest.java    From ribbon with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdating() throws Exception {
    EurekaNotificationServerListUpdater serverListUpdater = new EurekaNotificationServerListUpdater(
            new Provider<EurekaClient>() {
                @Override
                public EurekaClient get() {
                    return eurekaClientMock;
                }
            },
            testExecutor
    );

    try {
        Capture<EurekaEventListener> eventListenerCapture = new Capture<EurekaEventListener>();
        eurekaClientMock.registerEventListener(EasyMock.capture(eventListenerCapture));

        EasyMock.replay(eurekaClientMock);

        final AtomicBoolean firstTime = new AtomicBoolean(false);
        final CountDownLatch firstLatch = new CountDownLatch(1);
        final CountDownLatch secondLatch = new CountDownLatch(1);
        serverListUpdater.start(new ServerListUpdater.UpdateAction() {
            @Override
            public void doUpdate() {
                if (firstTime.compareAndSet(false, true)) {
                    firstLatch.countDown();
                } else {
                    secondLatch.countDown();
                }
            }
        });

        eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent());
        Assert.assertTrue(firstLatch.await(2, TimeUnit.SECONDS));
        // wait a bit for the updateQueued flag to be reset
        for (int i = 1; i < 10; i++) {
            if (serverListUpdater.updateQueued.get()) {
                Thread.sleep(i * 100);
            } else {
                break;
            }
        }

        eventListenerCapture.getValue().onEvent(new CacheRefreshedEvent());
        Assert.assertTrue(secondLatch.await(2, TimeUnit.SECONDS));
    } finally {
        serverListUpdater.stop();

        EasyMock.verify(eurekaClientMock);
    }
}
 
Example #16
Source File: EurekaServerStub.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
private void triggerCacheRefreshUpdate() {
    eventListeners.forEach(l -> l.onEvent(new CacheRefreshedEvent()));
}
 
Example #17
Source File: EurekaHostCallerIdResolver.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Override
public void onEvent(EurekaEvent event) {
    if (event instanceof CacheRefreshedEvent) {
        refreshAddressCache();
    }
}
 
Example #18
Source File: EurekaAgentStatusMonitor.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
@Override
public void onEvent(EurekaEvent event) {
    if (event instanceof CacheRefreshedEvent) {
        refreshAgentDiscoveryStatus();
    }
}
 
Example #19
Source File: EurekaClientLocalCacheRefreshedEvent.java    From summerframework with Apache License 2.0 4 votes vote down vote up
@Override
public CacheRefreshedEvent getSource() {
    return source;
}
 
Example #20
Source File: EurekaClientLocalCacheRefreshedEvent.java    From summerframework with Apache License 2.0 4 votes vote down vote up
public EurekaClientLocalCacheRefreshedEvent(CacheRefreshedEvent source) {
    super(source);
}