org.springframework.cloud.client.discovery.event.HeartbeatEvent Java Examples

The following examples show how to use org.springframework.cloud.client.discovery.event.HeartbeatEvent. 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: InstanceDiscoveryListenerTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_only_discover_new_instances_when_new_heartbeat_is_emitted() {
    Object heartbeat = new Object();
    listener.onParentHeartbeat(new ParentHeartbeatEvent(new Object(), heartbeat));

    when(discovery.getServices()).thenReturn(singletonList("service"));
    when(discovery.getInstances("service")).thenReturn(singletonList(new DefaultServiceInstance("test-1", "service",
        "localhost",
        80,
        false
    )));

    listener.onApplicationEvent(new HeartbeatEvent(new Object(), heartbeat));
    StepVerifier.create(registry.getInstances()).verifyComplete();

    listener.onApplicationEvent(new HeartbeatEvent(new Object(), new Object()));
    StepVerifier.create(registry.getInstances())
                .assertNext(a -> assertThat(a.getRegistration().getName()).isEqualTo("service"))
                .verifyComplete();
}
 
Example #2
Source File: DiscoveryClientConfigServiceBootstrapConfigurationTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRetryAndSucceedGetConfigServerInstanceFromDiscoveryClient()
		throws Exception {
	givenDiscoveryClientReturnsInfoOnThirdTry();

	setup("spring.cloud.config.discovery.enabled=true",
			"spring.cloud.config.retry.maxAttempts=3",
			"spring.cloud.config.retry.initialInterval=10",
			"spring.cloud.config.fail-fast=true");

	expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();
	verifyDiscoveryClientCalledThreeTimes();

	this.context.publishEvent(new HeartbeatEvent(this.context, "new"));

	expectConfigClientPropertiesHasConfigurationFromEureka();
}
 
Example #3
Source File: InstanceDiscoveryListenerTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_only_discover_new_instances_when_new_heartbeat_is_emitted() {
	Object heartbeat = new Object();
	this.listener.onParentHeartbeat(new ParentHeartbeatEvent(new Object(), heartbeat));

	when(this.discovery.getServices()).thenReturn(singletonList("service"));
	when(this.discovery.getInstances("service"))
			.thenReturn(singletonList(new DefaultServiceInstance("test-1", "service", "localhost", 80, false)));

	this.listener.onApplicationEvent(new HeartbeatEvent(new Object(), heartbeat));
	StepVerifier.create(this.registry.getInstances()).verifyComplete();

	this.listener.onApplicationEvent(new HeartbeatEvent(new Object(), new Object()));
	StepVerifier.create(this.registry.getInstances())
			.assertNext((a) -> assertThat(a.getRegistration().getName()).isEqualTo("service")).verifyComplete();
}
 
Example #4
Source File: DiscoveryClientRouteDefinitionLocatorIntegrationTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void newServiceAddsRoute() throws Exception {
	List<Route> routes = routeLocator.getRoutes()
			.filter(route -> route.getId().startsWith("test__")).collectList()
			.block();
	assertThat(routes).hasSize(1);

	discoveryClient.multiple();

	publisher.publishEvent(new HeartbeatEvent(this, 1L));

	Thread.sleep(2000);

	routes = routeLocator.getRoutes()
			.filter(route -> route.getId().startsWith("test__")).collectList()
			.block();
	assertThat(routes).hasSize(2);
}
 
Example #5
Source File: KubernetesCatalogWatchTest.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testEndpointsWithoutTargetRefs() {

	EndpointsList endpoints = createSingleEndpointEndpointListByPodName("api-pod");
	endpoints.getItems().get(0).getSubsets().get(0).getAddresses().get(0)
			.setTargetRef(null);

	when(this.endpointsOperation.list()).thenReturn(endpoints);
	when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);

	this.underTest.catalogServicesWatch();
	// second execution on shuffleServices
	this.underTest.catalogServicesWatch();

	verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
 
Example #6
Source File: KubernetesCatalogWatchTest.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
@Test
public void testEventBody() throws Exception {
	when(this.endpointsOperation.list()).thenReturn(
			createSingleEndpointEndpointListByPodName("api-pod", "other-pod"));
	when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);

	this.underTest.catalogServicesWatch();

	verify(this.applicationEventPublisher)
			.publishEvent(this.heartbeatEventArgumentCaptor.capture());

	HeartbeatEvent event = this.heartbeatEventArgumentCaptor.getValue();
	assertThat(event.getValue()).isInstanceOf(List.class);

	List<String> expectedPodsList = Arrays.asList("api-pod", "other-pod");
	assertThat(event.getValue()).isEqualTo(expectedPodsList);
}
 
Example #7
Source File: RouteRefreshListenerTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void onHeartbeatEvent() {
	ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class);
	RouteRefreshListener listener = new RouteRefreshListener(publisher);

	listener.onApplicationEvent(new HeartbeatEvent(this, 1L));
	listener.onApplicationEvent(new HeartbeatEvent(this, 1L));
	listener.onApplicationEvent(new HeartbeatEvent(this, 2L));

	verify(publisher, times(2)).publishEvent(any(RefreshRoutesEvent.class));
}
 
Example #8
Source File: CloudFoundryReactiveHeartbeatSender.java    From spring-cloud-cloudfoundry with Apache License 2.0 5 votes vote down vote up
@Scheduled(
		fixedDelayString = "${spring.cloud.cloudfoundry.discovery.heartbeatFrequency:5000}")
public void poll() {
	if (this.publisher != null) {
		this.publisher.publishEvent(
				new HeartbeatEvent(this.client, this.client.getServices()));
	}
}
 
Example #9
Source File: CloudFoundryHeartbeatSender.java    From spring-cloud-cloudfoundry with Apache License 2.0 5 votes vote down vote up
@Scheduled(
		fixedDelayString = "${spring.cloud.cloudfoundry.discovery.heartbeatFrequency:5000}")
public void poll() {
	if (this.publisher != null) {
		List<String> services = this.client.getServices();
		this.publisher.publishEvent(new HeartbeatEvent(this.client, services));
	}
}
 
Example #10
Source File: ConsulCatalogWatch.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@Timed("consul.watch-catalog-services")
public void catalogServicesWatch() {
	try {
		long index = -1;
		if (this.catalogServicesIndex.get() != null) {
			index = this.catalogServicesIndex.get().longValue();
		}

		CatalogServicesRequest request = CatalogServicesRequest.newBuilder()
				.setQueryParams(new QueryParams(
						this.properties.getCatalogServicesWatchTimeout(), index))
				.setToken(this.properties.getAclToken()).build();
		Response<Map<String, List<String>>> response = this.consul
				.getCatalogServices(request);
		Long consulIndex = response.getConsulIndex();
		if (consulIndex != null) {
			this.catalogServicesIndex.set(BigInteger.valueOf(consulIndex));
		}

		if (log.isTraceEnabled()) {
			log.trace("Received services update from consul: " + response.getValue()
					+ ", index: " + consulIndex);
		}
		this.publisher.publishEvent(new HeartbeatEvent(this, consulIndex));
	}
	catch (Exception e) {
		log.error("Error watching Consul CatalogServices", e);
	}
}
 
Example #11
Source File: DiscoveryClientConfigServiceBootstrapConfiguration.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
	if (event instanceof ContextRefreshedEvent) {
		startup((ContextRefreshedEvent) event);
	}
	else if (event instanceof HeartbeatEvent) {
		heartbeat((HeartbeatEvent) event);
	}
}
 
Example #12
Source File: CloudEurekaClient.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCacheRefreshed() {
	super.onCacheRefreshed();

	if (this.cacheRefreshedCount != null) { // might be called during construction and
		// will be null
		long newCount = this.cacheRefreshedCount.incrementAndGet();
		log.trace("onCacheRefreshed called with count: " + newCount);
		this.publisher.publishEvent(new HeartbeatEvent(this, newCount));
	}
}
 
Example #13
Source File: ZookeeperServiceWatch.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event)
		throws Exception {
	if (event.getType().equals(TreeCacheEvent.Type.NODE_ADDED)
			|| event.getType().equals(TreeCacheEvent.Type.NODE_REMOVED)
			|| event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
		long newCacheChange = this.cacheChange.incrementAndGet();
		this.publisher.publishEvent(new HeartbeatEvent(this, newCacheChange));
	}
}
 
Example #14
Source File: DiscoverConfigServerBootstrapConfiguration.java    From spring-cloud-lattice with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
	if (event instanceof ContextRefreshedEvent) {
		refresh();
	}
	else if (event instanceof HeartbeatEvent) {
		if (this.monitor.update(((HeartbeatEvent) event).getValue())) {
			refresh();
		}
	}
}
 
Example #15
Source File: LandscapeWatcher.java    From microservices-dashboard with Apache License 2.0 5 votes vote down vote up
@EventListener({ HeartbeatEvent.class })
public void discoverLandscape() {
	logger.debug("Discovering landscape");

	List<String> applications = this.discoveryClient.getServices()
			.stream()
			.filter(this.applicationFilters)
			.collect(Collectors.toList());

	Catalog catalog = this.catalogService.getCatalog();
	dispatchEventForDiscoveredApplications(applications, catalog);
	dispatchEventForDisappearedApplications(applications, catalog);

	applications.forEach(this::processApplication);
}
 
Example #16
Source File: MossInstanceDiscoveryListener.java    From Moss with Apache License 2.0 5 votes vote down vote up
@EventListener
public void onApplicationEvent(HeartbeatEvent event) {
    Map<String, ConsulDiscoveryClient> map = multRegisterCenter.getMultConsulMap();
    map.entrySet().forEach(e -> {
        HeartbeatMonitor heartbeatMonitor = getHeartbeatMonitorByClient(e.getValue());
        threadLocalmonitor.set(heartbeatMonitor);
        discoverIfNeeded(e.getValue(), event.getValue());
        threadLocalmonitor.remove();
    });

}
 
Example #17
Source File: DiscoveryClientResolverFactory.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Triggers a refresh of the registered name resolvers.
 *
 * @param event The event that triggered the update.
 */
@EventListener(HeartbeatEvent.class)
public void heartbeat(final HeartbeatEvent event) {
    if (this.monitor.update(event.getValue())) {
        for (final DiscoveryClientNameResolver discoveryClientNameResolver : this.discoveryClientNameResolvers) {
            discoveryClientNameResolver.refreshFromExternal();
        }
    }
}
 
Example #18
Source File: MossInstanceDiscoveryListener.java    From Moss with Apache License 2.0 5 votes vote down vote up
@EventListener
public void onApplicationEvent(HeartbeatEvent event) {
    HeartbeatMonitor heartbeatMonitor= getHeartbeatMonitorByClient((CloudEurekaClient) event.getSource());
    threadLocalmonitor.set(heartbeatMonitor);
    discoverIfNeeded((CloudEurekaClient) event.getSource(),event.getValue());
    threadLocalmonitor.remove();
}
 
Example #19
Source File: KubernetesCatalogWatchTest.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndpointsWithoutAddresses() {

	EndpointsList endpoints = createSingleEndpointEndpointListByPodName("api-pod");
	endpoints.getItems().get(0).getSubsets().get(0).setAddresses(null);

	when(this.endpointsOperation.list()).thenReturn(endpoints);
	when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);

	this.underTest.catalogServicesWatch();
	// second execution on shuffleServices
	this.underTest.catalogServicesWatch();

	verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
 
Example #20
Source File: KubernetesCatalogWatchTest.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndpointsWithoutSubsets() {

	EndpointsList endpoints = createSingleEndpointEndpointListWithoutSubsets();

	when(this.endpointsOperation.list()).thenReturn(endpoints);
	when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);

	this.underTest.catalogServicesWatch();
	// second execution on shuffleServices
	this.underTest.catalogServicesWatch();

	verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
 
Example #21
Source File: KubernetesCatalogWatchTest.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
@Test
public void testRandomOrderChangeServices() throws Exception {
	when(this.endpointsOperation.list())
			.thenReturn(
					createEndpointsListByServiceName("api-service", "other-service"))
			.thenReturn(
					createEndpointsListByServiceName("other-service", "api-service"));
	when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);

	this.underTest.catalogServicesWatch();
	// second execution on shuffleServices
	this.underTest.catalogServicesWatch();

	verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
 
Example #22
Source File: DubboServiceDiscoveryAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public DubboServiceDiscoveryAutoConfiguration(
		DubboServiceMetadataRepository dubboServiceMetadataRepository,
		ApplicationEventPublisher applicationEventPublisher,
		DiscoveryClient discoveryClient,
		ObjectProvider<Predicate<HeartbeatEvent>> heartbeatEventChangedPredicate) {
	this.dubboServiceMetadataRepository = dubboServiceMetadataRepository;
	this.applicationEventPublisher = applicationEventPublisher;
	this.discoveryClient = discoveryClient;
	this.heartbeatEventChangedPredicate = heartbeatEventChangedPredicate;
}
 
Example #23
Source File: DubboServiceDiscoveryAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
/**
 * The default {@link Predicate} implementation of {@link HeartbeatEvent} based on the
 * comparison between previous and current {@link HeartbeatEvent#getValue() state
 * value}, the {@link DiscoveryClient} implementation may override current.
 * @return {@link Predicate} {@link HeartbeatEvent}
 * @see EurekaConfiguration#heartbeatEventChangedPredicate()
 */
@Bean
@ConditionalOnMissingBean
public Predicate<HeartbeatEvent> defaultHeartbeatEventChangePredicate() {
	return event -> {
		Object oldState = heartbeatState.get();
		Object newState = event.getValue();
		return heartbeatState.compareAndSet(oldState, newState)
				&& !Objects.equals(oldState, newState);
	};
}
 
Example #24
Source File: DubboServiceDiscoveryAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
/**
 * Compare {@link Applications#getAppsHashCode() apps hash code} between last
 * {@link Applications} and current.
 *
 * @see Applications#getAppsHashCode()
 * @return HeartbeatEvent Predicate
 */
@Bean
public Predicate<HeartbeatEvent> heartbeatEventChangedPredicate() {
	return event -> {
		String oldAppsHashCode = appsHashCodeCache.get();
		CloudEurekaClient cloudEurekaClient = (CloudEurekaClient) event
				.getSource();
		Applications applications = cloudEurekaClient.getApplications();
		String appsHashCode = applications.getAppsHashCode();
		return appsHashCodeCache.compareAndSet(oldAppsHashCode, appsHashCode)
				&& !Objects.equals(oldAppsHashCode, appsHashCode);
	};
}
 
Example #25
Source File: DiscoveryClientResolverFactory.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Triggers a refresh of the registered name resolvers.
 *
 * @param event The event that triggered the update.
 */
@EventListener(HeartbeatEvent.class)
public void heartbeat(final HeartbeatEvent event) {
    if (this.monitor.update(event.getValue())) {
        for (final DiscoveryClientNameResolver discoveryClientNameResolver : this.discoveryClientNameResolvers) {
            discoveryClientNameResolver.refreshFromExternal();
        }
    }
}
 
Example #26
Source File: EurekaCacheRefreshListener.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(HeartbeatEvent event) {
    Object count = event.getValue();
    Object source = event.getSource();

    logger.info("start onApplicationEvent, count [{}], source :\n{}", count, JSON.toJSON(source));
}
 
Example #27
Source File: KubernetesCatalogWatchTest.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
@Test
public void testRandomOrderChangePods() throws Exception {
	when(this.endpointsOperation.list())
			.thenReturn(
					createSingleEndpointEndpointListByPodName("api-pod", "other-pod"))
			.thenReturn(createSingleEndpointEndpointListByPodName("other-pod",
					"api-pod"));
	when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);

	this.underTest.catalogServicesWatch();
	// second execution on shuffleServices
	this.underTest.catalogServicesWatch();

	verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
 
Example #28
Source File: KubernetesCatalogWatch.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
@Scheduled(
		fixedDelayString = "${spring.cloud.kubernetes.discovery.catalogServicesWatchDelay:30000}")
public void catalogServicesWatch() {
	try {
		List<String> previousState = this.catalogEndpointsState.get();

		// not all pods participate in the service discovery. only those that have
		// endpoints.
		List<Endpoints> endpoints = this.properties.isAllNamespaces()
				? this.kubernetesClient.endpoints().inAnyNamespace().list().getItems()
				: this.kubernetesClient.endpoints().list().getItems();
		List<String> endpointsPodNames = endpoints.stream().map(Endpoints::getSubsets)
				.filter(Objects::nonNull).flatMap(Collection::stream)
				.map(EndpointSubset::getAddresses).filter(Objects::nonNull)
				.flatMap(Collection::stream).map(EndpointAddress::getTargetRef)
				.filter(Objects::nonNull).map(ObjectReference::getName) // pod name
																		// unique in
																		// namespace
				.sorted(String::compareTo).collect(Collectors.toList());

		this.catalogEndpointsState.set(endpointsPodNames);

		if (!endpointsPodNames.equals(previousState)) {
			logger.trace("Received endpoints update from kubernetesClient: {}",
					endpointsPodNames);
			this.publisher.publishEvent(new HeartbeatEvent(this, endpointsPodNames));
		}
	}
	catch (Exception e) {
		logger.error("Error watching Kubernetes Services", e);
	}
}
 
Example #29
Source File: MossInstanceDiscoveryListener.java    From Moss with Apache License 2.0 4 votes vote down vote up
@EventListener
public void onApplicationEvent(HeartbeatEvent event) {
    discoverIfNeeded(event.getValue());
}
 
Example #30
Source File: MossInstanceDiscoveryListener.java    From Moss with Apache License 2.0 4 votes vote down vote up
@EventListener
public void onApplicationEvent(HeartbeatEvent event) {
    discoverIfNeeded(event.getValue());
}