Java Code Examples for com.netflix.appinfo.ApplicationInfoManager

The following examples show how to use com.netflix.appinfo.ApplicationInfoManager. These examples are extracted from open source projects. 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 Project: api-layer   Source File: DiscoveryClientConfig.java    License: 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
@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 Project: chassis   Source File: ChassisConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
    //we only want to tell Eureka that the application is up
    //when the root application context (thisApplicationContext) has
    //been fully started.  we want to ignore any ContextRefreshedEvent
    //from child application contexts.
    if (!event.getSource().equals(thisApplicationContext)) {
        return;
    }
    if (event instanceof ContextRefreshedEvent) {
        if (!disableEureka) {
            // tell Eureka the server UP which in turn starts the health checks and heartbeat
            ApplicationInfoManager.getInstance().setInstanceStatus(InstanceStatus.UP);
        }
    } else if (event instanceof ContextClosedEvent) {
        if (!disableEureka) {
            ApplicationInfoManager.getInstance().setInstanceStatus(InstanceStatus.DOWN);
        }
    }
}
 
Example 4
Source Project: chassis   Source File: ChassisEurekaRegistrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
 public void testServiceRegistration() throws InterruptedException {
 	// Registers "chasis-default-name" with a Eurkea server running on local host.
 	//   http://localhost:8184/v2/apps/chassis-default-name

 	// tell eureka the service is up which causes a registration
 	ApplicationInfoManager.getInstance().setInstanceStatus(InstanceInfo.InstanceStatus.UP);
 	
 	// get application registration from Eureka
 	DiscoveryClient client = DiscoveryManager.getInstance().getDiscoveryClient();
 	InstanceInfo instanceInfo = null;
 	for (int i = 0; (instanceInfo == null) && (i < 50); i++) {
 		Thread.sleep(5000);
 		try {
	instanceInfo =  client.getNextServerFromEureka("default-service", false);
} catch (RuntimeException e) {
	// eat not found runtime exception
}
 	}
 	Assert.assertNotNull(instanceInfo);
 	Assert.assertEquals(InstanceStatus.UP, instanceInfo.getStatus());
 	System.out.println("done");
 }
 
Example 5
@Bean
public EurekaServerContext testEurekaServerContext(ServerCodecs serverCodecs,
		PeerAwareInstanceRegistry registry, PeerEurekaNodes peerEurekaNodes,
		ApplicationInfoManager applicationInfoManager,
		EurekaServerConfig eurekaServerConfig) {
	return new DefaultEurekaServerContext(eurekaServerConfig, serverCodecs,
			registry, peerEurekaNodes, applicationInfoManager) {
		@Override
		public void shutdown() {
			logger.info(
					"Shutting down (except ServoControl and EurekaMonitors)..");
			registry.shutdown();
			peerEurekaNodes.shutdown();
			// ServoControl.shutdown();
			// EurekaMonitors.shutdown();
			logger.info("Shut down");
		}
	};
}
 
Example 6
Source Project: spring-cloud-netflix   Source File: EurekaRegistration.java    License: Apache License 2.0 6 votes vote down vote up
public EurekaRegistration build() {
	Assert.notNull(instanceConfig, "instanceConfig may not be null");

	if (this.applicationInfoManager == null) {
		InstanceInfo instanceInfo = new InstanceInfoFactory()
				.create(this.instanceConfig);
		this.applicationInfoManager = new ApplicationInfoManager(
				this.instanceConfig, instanceInfo);
	}
	if (this.eurekaClient == null) {
		Assert.notNull(this.clientConfig,
				"if eurekaClient is null, EurekaClientConfig may not be null");
		Assert.notNull(this.publisher,
				"if eurekaClient is null, ApplicationEventPublisher may not be null");

		this.eurekaClient = new CloudEurekaClient(this.applicationInfoManager,
				this.clientConfig, this.publisher);
	}
	return new EurekaRegistration(instanceConfig, eurekaClient,
			applicationInfoManager, healthCheckHandler);
}
 
Example 7
@Test
public void eurekaClientNotShutdownInDeregister() {
	EurekaServiceRegistry registry = new EurekaServiceRegistry();

	CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class);
	ApplicationInfoManager applicationInfoManager = mock(
			ApplicationInfoManager.class);

	when(applicationInfoManager.getInfo()).thenReturn(mock(InstanceInfo.class));

	EurekaRegistration registration = EurekaRegistration
			.builder(new EurekaInstanceConfigBean(
					new InetUtils(new InetUtilsProperties())))
			.with(eurekaClient).with(applicationInfoManager)
			.with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class))
			.build();

	registry.deregister(registration);

	verifyNoInteractions(eurekaClient);
}
 
Example 8
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean(value = EurekaClient.class,
		search = SearchStrategy.CURRENT)
public EurekaClient eurekaClient(ApplicationInfoManager manager,
		EurekaClientConfig config, ApplicationContext context) {
	return new CloudEurekaClient(manager, config, null, context) {
		@Override
		public synchronized void shutdown() {
			CountDownLatch latch = countDownLatch();
			if (latch.getCount() == 1) {
				latch.countDown();
			}
			super.shutdown();
		}
	};
}
 
Example 9
Source Project: zuul   Source File: BaseServerStartup.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
public BaseServerStartup(ServerStatusManager serverStatusManager, FilterLoader filterLoader,
                         SessionContextDecorator sessionCtxDecorator, FilterUsageNotifier usageNotifier,
                         RequestCompleteHandler reqCompleteHandler, Registry registry,
                         DirectMemoryMonitor directMemoryMonitor, EventLoopGroupMetrics eventLoopGroupMetrics,
                         EurekaClient discoveryClient, ApplicationInfoManager applicationInfoManager,
                         AccessLogPublisher accessLogPublisher)
{
    this.serverStatusManager = serverStatusManager;
    this.registry = registry;
    this.directMemoryMonitor = directMemoryMonitor;
    this.eventLoopGroupMetrics = eventLoopGroupMetrics;
    this.discoveryClient = discoveryClient;
    this.applicationInfoManager = applicationInfoManager;
    this.accessLogPublisher = accessLogPublisher;
    this.sessionCtxDecorator = sessionCtxDecorator;
    this.reqCompleteHandler = reqCompleteHandler;
    this.filterLoader = filterLoader;
    this.usageNotifier = usageNotifier;
}
 
Example 10
Source Project: mPaaS   Source File: DiscoveryServerConfig.java    License: Apache License 2.0 5 votes vote down vote up
public CustomRefreshablePeerEurekaNodes(
        final PeerAwareInstanceRegistry registry,
        final EurekaServerConfig serverConfig,
        final EurekaClientConfig clientConfig,
        final ServerCodecs serverCodecs,
        final ApplicationInfoManager applicationInfoManager) {
    super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager);
}
 
Example 11
Source Project: Moss   Source File: MultRegisterCenterServerMgmtConfig.java    License: Apache License 2.0 5 votes vote down vote up
public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient,
                                             CloudEurekaInstanceConfig instanceConfig,
                                             ApplicationInfoManager applicationInfoManager,
                                             @Autowired(required = false) ObjectProvider<HealthCheckHandler> healthCheckHandler) {
    return EurekaRegistration.builder(instanceConfig)
            .with(applicationInfoManager)
            .with(eurekaClient)
            .with(healthCheckHandler)
            .build();
}
 
Example 12
Source Project: Moss   Source File: MultRegisterCenterServerMgmtConfig.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 动态添加一个注册中心
 *
 * @param registerCenterCode
 * @param registerCenterUrl
 */
public void addEureka(String registerCenterCode, String registerCenterUrl) {

    ManagementMetadataProvider managementMetadataProvider = serviceManagementMetadataProvider();
    EurekaClientConfigBean configBean = eurekaClientConfigBean(env);
    configBean.getServiceUrl().clear();
    configBean.getServiceUrl().put(EurekaClientConfigBean.DEFAULT_ZONE, registerCenterUrl);
    EurekaInstanceConfigBean instanceConfigBean = eurekaInstanceConfigBean(inetUtils, env, managementMetadataProvider);
    instanceConfigBean.setEnvironment(env);
    instanceConfigBean.setAppname(instanceConfigBean.getAppname());
    ApplicationInfoManager manager = eurekaApplicationInfoManager(instanceConfigBean);


    /**
     * 添加EurekaClient,如果有就先删除,再添加
     */
    Map<String, EurekaClient> multEurekaMap = multRegisterCenter.getMultEurekaMap();
    revomeEurekaClientByCode(registerCenterCode);
    EurekaClient eurekaClient = eurekaClient(manager, configBean);
    multEurekaMap.put(registerCenterCode, eurekaClient);
    multRegisterCenter.getMultEurekaCodeMap().put(eurekaClient, registerCenterCode);

    /**
     * 添加autoServiceRegistration,如果有就先删除,再添加
     */
    Map<String, MossEurekaAutoServiceRegistration> multRegistrationMap = multRegisterCenter.getMultRegistrationMap();
    revomeServiceRegistration(registerCenterCode);
    EurekaRegistration registration = eurekaRegistration(eurekaClient, instanceConfigBean, manager, healthCheckHandler);
    MossEurekaAutoServiceRegistration autoServiceRegistration = eurekaAutoServiceRegistration(context, eurekaServiceRegistry(), registration, registration);
    autoServiceRegistration.start();
    multRegistrationMap.put(registerCenterCode, autoServiceRegistration);

    /**
     * 添加 HeartbeatMonitor
     */
    Map<EurekaClient, HeartbeatMonitor> multHeartbeatMonitorMap = multRegisterCenter.getMultHeartbeatMonitorMap();
    multHeartbeatMonitorMap.remove(registerCenterCode);
    multHeartbeatMonitorMap.put(eurekaClient, new HeartbeatMonitor());

}
 
Example 13
Source Project: summerframework   Source File: ScheduleReportServerLoad.java    License: Apache License 2.0 5 votes vote down vote up
public void start() {
    ScheduledExecutorService scheduleReport = Executors.newScheduledThreadPool(1, new NamedThreadFactory());
    scheduleReport.scheduleAtFixedRate(new Runnable() {

        @Override
        @SuppressWarnings("deprecation")
        public void run() {
            try {
                Map<String, String> map = ApplicationInfoManager.getInstance().getInfo().getMetadata();
                ServerLoadStatus serverLoadStatus = new ServerLoadStatus();
                serverLoadStatus.calculateSystemInfo();
                String serverLoadStatusJson = JsonUtil.toJson(serverLoadStatus);
                map.put(Constants.EUREKA_METADATA_SERVERLOAD, serverLoadStatusJson);

                Assert.notNull(registration, "registration MUST NOT BE NULL");
                Assert.notNull(registration.getMetadata(), "registration.getMetadata() MUST NOT BE NULL");
                Assert.notNull(ApplicationInfoManager.getInstance(),
                    "ApplicationInfoManager.getInstance() MUST NOT BE NULL");
                Assert.notNull(ApplicationInfoManager.getInstance().getInfo(),
                    "ApplicationInfoManager.getInstance().getInfo() MUST NOT BE NULL");
                Assert.notNull(ApplicationInfoManager.getInstance().getInfo().getMetadata(),
                    "ApplicationInfoManager.getInstance().getInfo().getMetadata() MUST NOT BE NULL");

                map.putAll(registration.getMetadata());

                ApplicationInfoManager.getInstance().registerAppMetadata(map);
            } catch (Throwable e) {
                LOGGER.error(e.getMessage(), e);
            }

        }
    }, 0, 60, TimeUnit.SECONDS);
}
 
Example 14
public EurekaRegisterHandler(EurekaClient client, TarsEurekaInstance instanceConfig,
                             HealthCheckHandler healthCheckHandler, ApplicationInfoManager applicationInfoManager) {
    this.client = client;
    this.instanceConfig = instanceConfig;
    this.healthCheckHandler = healthCheckHandler;
    this.applicationInfoManager = applicationInfoManager;
}
 
Example 15
Source Project: s2g-zuul   Source File: InitializeServletListener.java    License: MIT License 5 votes vote down vote up
private void registerEureka() {
	DynamicBooleanProperty eurekaEnabled = DynamicPropertyFactory.getInstance().getBooleanProperty("eureka.enabled",
			true);
	if (!eurekaEnabled.get())
		return;

	EurekaInstanceConfig eurekaInstanceConfig = new PropertiesInstanceConfig() {
	};
       ConfigurationManager.getConfigInstance().setProperty("eureka.statusPageUrl","http://"+ getTurbineInstance());

	DiscoveryManager.getInstance().initComponent(eurekaInstanceConfig, new DefaultEurekaClientConfig());

	final DynamicStringProperty serverStatus = DynamicPropertyFactory.getInstance()
			.getStringProperty("server." + IPUtil.getLocalIP() + ".status", "up");
	DiscoveryManager.getInstance().getDiscoveryClient().registerHealthCheckCallback(new HealthCheckCallback() {
		@Override
		public boolean isHealthy() {
			return serverStatus.get().toLowerCase().equals("up");
		}
	});

	String version = String.valueOf(System.currentTimeMillis());
	String group = ConfigurationManager.getConfigInstance().getString("server.group", "default");
	String dataCenter = ConfigurationManager.getConfigInstance().getString("server.data-center", "default");

	Map<String, String> metadata = new HashMap<String, String>();
	metadata.put("version", version);
	metadata.put("group", group);
	metadata.put("dataCenter", dataCenter);

	String turbineInstance = getTurbineInstance();
	if (turbineInstance != null) {
		metadata.put("turbine.instance", turbineInstance);
	}

	ApplicationInfoManager.getInstance().registerAppMetadata(metadata);
}
 
Example 16
Source Project: api-layer   Source File: ApimlDiscoveryClient.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public ApimlDiscoveryClient(
    ApplicationInfoManager applicationInfoManager,
    EurekaClientConfig config,
    AbstractDiscoveryClientOptionalArgs<?> args,
    ApplicationEventPublisher publisher
) {
    super(applicationInfoManager, config, args, publisher);
    init();
}
 
Example 17
@Test
public void invalidateToken() {
    TokenAuthentication tokenAuthentication;

    String jwt1 = authService.createJwtToken("user1", "domain1", "ltpa1");
    assertFalse(authService.isInvalidated(jwt1));
    tokenAuthentication = authService.validateJwtToken(jwt1);
    assertTrue(tokenAuthentication.isAuthenticated());

    InstanceInfo myInstance = mock(InstanceInfo.class);
    when(myInstance.getInstanceId()).thenReturn("myInstance01");
    ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class);
    when(applicationInfoManager.getInfo()).thenReturn(myInstance);
    when(discoveryClient.getApplicationInfoManager()).thenReturn(applicationInfoManager);
    when(restTemplate.exchange(eq(zosmfUrl + "/zosmf/services/authenticate"), eq(HttpMethod.DELETE), any(), eq(String.class)))
        .thenReturn(new ResponseEntity<>(HttpStatus.OK));

    Application application = mock(Application.class);
    List<InstanceInfo> instances = Arrays.asList(
        createInstanceInfo("instance02", "hostname1", 10000, 10433),
        createInstanceInfo("myInstance01", "localhost", 10000, 10433),
        createInstanceInfo("instance03", "hostname2", 10001, 0)
    );
    when(application.getInstances()).thenReturn(instances);
    when(discoveryClient.getApplication("gateway")).thenReturn(application);

    authService.invalidateJwtToken(jwt1, true);
    assertTrue(authService.isInvalidated(jwt1));
    tokenAuthentication = authService.validateJwtToken(jwt1);
    assertFalse(tokenAuthentication.isAuthenticated());
    verify(restTemplate, times(2)).delete(anyString(), (Object[]) any());
    verify(restTemplate).delete("https://hostname1:10433/gateway/auth/invalidate/{}", jwt1);
    verify(restTemplate).delete("http://hostname2:10001/gateway/auth/invalidate/{}", jwt1);
    verify(restTemplate, times(1))
        .exchange(eq(zosmfUrl + "/zosmf/services/authenticate"), eq(HttpMethod.DELETE), any(), eq(String.class));
}
 
Example 18
Source Project: api-layer   Source File: ApiMediationClientImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Registers this service with Eureka server using EurekaClient which is initialized with the provided {@link ApiMediationServiceConfig} methods parameter.
 * Successive calls to {@link #register} method without intermediate call to {@linl #unregister} will be rejected with exception.
 * <p>
 * This method catches all RuntimeException, and rethrows {@link ServiceDefinitionException} checked exception.
 *
 * @param config
 * @throws ServiceDefinitionException
 */
@Override
public synchronized void register(ApiMediationServiceConfig config) throws ServiceDefinitionException {
    if (eurekaClient != null) {
        throw new ServiceDefinitionException("EurekaClient was previously registered for this instance of ApiMediationClient. Call your ApiMediationClient unregister() method before attempting other registration.");
    }

    EurekaClientConfig clientConfiguration = eurekaClientConfigProvider.config(config);
    ApplicationInfoManager infoManager = initializeApplicationInfoManager(config);
    eurekaClient = initializeEurekaClient(infoManager, clientConfiguration, config);
}
 
Example 19
Source Project: api-layer   Source File: ApiMediationClientImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create and initialize EurekaClient instance.
 *
 * @param applicationInfoManager
 * @param clientConfig
 * @param config
 * @return Initialized {@link DiscoveryClient} instance - an implementation of {@link EurekaClient}
 */
private EurekaClient initializeEurekaClient(
    ApplicationInfoManager applicationInfoManager, EurekaClientConfig clientConfig, ApiMediationServiceConfig config) {

    Ssl sslConfig = config.getSsl();

    HttpsConfig.HttpsConfigBuilder builder = HttpsConfig.builder();
    if (sslConfig != null) {
        builder.protocol(sslConfig.getProtocol());
        if (Boolean.TRUE.equals(sslConfig.getEnabled())) {
            builder.keyAlias(sslConfig.getKeyAlias())
                .keyStore(sslConfig.getKeyStore())
                .keyPassword(sslConfig.getKeyPassword())
                .keyStorePassword(sslConfig.getKeyStorePassword())
                .keyStoreType(sslConfig.getKeyStoreType());
        }

        builder.verifySslCertificatesOfServices(Boolean.TRUE.equals(sslConfig.getVerifySslCertificatesOfServices()));
        if (Boolean.TRUE.equals(sslConfig.getVerifySslCertificatesOfServices())) {
            builder.trustStore(sslConfig.getTrustStore())
                .trustStoreType(sslConfig.getTrustStoreType())
                .trustStorePassword(sslConfig.getTrustStorePassword());
        }
    }
    HttpsConfig httpsConfig = builder.build();

    HttpsFactory factory = new HttpsFactory(httpsConfig);
    EurekaJerseyClient eurekaJerseyClient = factory.createEurekaJerseyClientBuilder(
        config.getDiscoveryServiceUrls().get(0), config.getServiceId()).build();

    AbstractDiscoveryClientOptionalArgs args = new DiscoveryClient.DiscoveryClientOptionalArgs();
    args.setEurekaJerseyClient(eurekaJerseyClient);
    applicationInfoManager.setInstanceStatus(InstanceInfo.InstanceStatus.UP);
    return this.eurekaClientProvider.client(applicationInfoManager, clientConfig, args);
}
 
Example 20
Source Project: oneplatform   Source File: EurekaRegistry.java    License: Apache License 2.0 5 votes vote down vote up
private void initEurekaClient(Properties properties) throws Exception{
	
	properties.setProperty("eureka.metadataMap.nodeId", NodeNameHolder.getNodeId());
	ConfigurationManager.loadProperties(properties);
	//ConfigurationManager.loadPropertiesFromResources("eureka.properties");
	
	//DynamicPropertyFactory configInstance = com.netflix.config.DynamicPropertyFactory.getInstance();
	
	MyDataCenterInstanceConfig instanceConfig = new MyDataCenterInstanceConfig(){
		@Override
		public String getHostName(boolean refresh) {
			String hostName = super.getHostName(refresh);
			if(ResourceUtils.getBoolean("eureka.preferIpAddress")){
				hostName = IpUtils.getLocalIpAddr();
			}
			return hostName;
		}

		@Override
		public String getIpAddress() {
			return IpUtils.getLocalIpAddr();
		}
		
		
	};
	InstanceInfo instanceInfo = new EurekaConfigBasedInstanceInfoProvider(instanceConfig).get();
       applicationInfoManager = new ApplicationInfoManager(instanceConfig, instanceInfo);
       
       DefaultEurekaClientConfig clientConfig = new DefaultEurekaClientConfig();

       eurekaClient = new DiscoveryClient(applicationInfoManager, clientConfig);
       
       instanceId = instanceInfo.getInstanceId();
}
 
Example 21
Source Project: didi-eureka-server   Source File: EurekaServerBootstrap.java    License: MIT License 5 votes vote down vote up
public EurekaServerBootstrap(ApplicationInfoManager applicationInfoManager,
		EurekaClientConfig eurekaClientConfig, EurekaServerConfig eurekaServerConfig,
		PeerAwareInstanceRegistry registry, EurekaServerContext serverContext) {
	this.applicationInfoManager = applicationInfoManager;
	this.eurekaClientConfig = eurekaClientConfig;
	this.eurekaServerConfig = eurekaServerConfig;
	this.registry = registry;
	this.serverContext = serverContext;
}
 
Example 22
Source Project: didi-eureka-server   Source File: EurekaControllerTest.java    License: MIT License 5 votes vote down vote up
@Before
public void setup() throws Exception {
	PeerEurekaNodes peerEurekaNodes = mock(PeerEurekaNodes.class);
	when(peerEurekaNodes.getPeerNodesView()).thenReturn(Collections.<PeerEurekaNode>emptyList());

	InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder()
			.setAppName("test")
			.setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn))
			.build();

	this.infoManager = mock(ApplicationInfoManager.class);
	this.original = ApplicationInfoManager.getInstance();
	setInstance(this.infoManager);
	when(this.infoManager.getInfo()).thenReturn(instanceInfo);

	Application myapp = new Application("myapp");
	myapp.addInstance(InstanceInfo.Builder.newBuilder()
			.setAppName("myapp")
			.setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn))
			.setInstanceId("myapp:1")
			.build());

	ArrayList<Application> applications = new ArrayList<>();
	applications.add(myapp);

	PeerAwareInstanceRegistry registry = mock(PeerAwareInstanceRegistry.class);
	when(registry.getSortedApplications()).thenReturn(applications);

	EurekaServerContext serverContext = mock(EurekaServerContext.class);
	EurekaServerContextHolder.initialize(serverContext);
	when(serverContext.getRegistry()).thenReturn(registry);
	when(serverContext.getPeerEurekaNodes()).thenReturn(peerEurekaNodes);
	when(serverContext.getApplicationInfoManager()).thenReturn(this.infoManager);

}
 
Example 23
Source Project: didi-eureka-server   Source File: EurekaCustomPeerNodesTest.java    License: MIT License 5 votes vote down vote up
@Bean
public PeerEurekaNodes myPeerEurekaNodes(PeerAwareInstanceRegistry registry,
		EurekaServerConfig eurekaServerConfig,
		EurekaClientConfig eurekaClientConfig, ServerCodecs serverCodecs,
		ApplicationInfoManager applicationInfoManager) {
	return new CustomEurekaPeerNodes(registry, eurekaServerConfig,
			eurekaClientConfig, serverCodecs, applicationInfoManager);
}
 
Example 24
Source Project: didi-eureka-server   Source File: EurekaCustomPeerNodesTest.java    License: MIT License 5 votes vote down vote up
public CustomEurekaPeerNodes(PeerAwareInstanceRegistry registry,
		EurekaServerConfig serverConfig, EurekaClientConfig clientConfig,
		ServerCodecs serverCodecs,
		ApplicationInfoManager applicationInfoManager) {
	super(registry, serverConfig, clientConfig, serverCodecs,
			applicationInfoManager);
}
 
Example 25
@Test
public void testHealthCheckHandlerRegistered() {
    InjectorBuilder.fromModules(new EurekaHealthStatusBridgeModule(), new AbstractModule() {
        @Override
        protected void configure() {
            bind(ApplicationInfoManager.class).toInstance(infoManager);
            bind(EurekaClient.class).toInstance(eurekaClient);
            bind(HealthCheckAggregator.class).toInstance(healthCheckAggregator);
        }
    }).createInjector();
    Mockito.verify(eurekaClient, Mockito.times(1)).registerHealthCheck(Mockito.any(HealthCheckHandler.class));
}
 
Example 26
Source Project: kork   Source File: BootHealthCheckHandler.java    License: Apache License 2.0 5 votes vote down vote up
public BootHealthCheckHandler(
    ApplicationInfoManager applicationInfoManager,
    HealthAggregator aggregator,
    Map<String, HealthIndicator> healthIndicators) {
  this.applicationInfoManager =
      Objects.requireNonNull(applicationInfoManager, "applicationInfoManager");
  this.aggregateHealth = new CompositeHealthIndicator(aggregator, healthIndicators);
}
 
Example 27
Source Project: chassis   Source File: MetadataCollector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Update Eurkea if the metadata has changed since the last poll.
 */
@Scheduled(fixedDelay = 30000)
private void updateMetaData() {
    // Early out if Eureka has NOT been initialized.
    InstanceInfo instanceInfo = ApplicationInfoManager.getInstance().getInfo();
    if (instanceInfo == null) {
        return;
    }

    // Early out if we only have static metadata since that has already
    // been reported to Eureka.
    Map<String, String> dynamic = getDynamicMetadataMap();
    if (dynamic == null) {
        return;
    }

    // Early out if dynamic metadata has not changed since the last poll.
    if (oldMetaData != null && dynamic.size() == oldMetaData.size()) {
        boolean different = false;
        for (Map.Entry<String,String> kvp : dynamic.entrySet()) {
            if (!kvp.getValue().equals(oldMetaData.get(kvp.getKey()))) {
                different = true;
                break;
            }
        }
        if (!different) {
            return;
        }
    }

    // Update the instance info which will eventually get replicated to the eureka servers.
    // Note that registerAppMetadata is additive so we just need to include the dynamic values
    // since it already has the static ones.
    oldMetaData = dynamic;
    ApplicationInfoManager.getInstance().registerAppMetadata( dynamic );
}
 
Example 28
public EurekaServerBootstrap(ApplicationInfoManager applicationInfoManager,
		EurekaClientConfig eurekaClientConfig, EurekaServerConfig eurekaServerConfig,
		PeerAwareInstanceRegistry registry, EurekaServerContext serverContext) {
	this.applicationInfoManager = applicationInfoManager;
	this.eurekaClientConfig = eurekaClientConfig;
	this.eurekaServerConfig = eurekaServerConfig;
	this.registry = registry;
	this.serverContext = serverContext;
}
 
Example 29
RefreshablePeerEurekaNodes(final PeerAwareInstanceRegistry registry,
		final EurekaServerConfig serverConfig,
		final EurekaClientConfig clientConfig, final ServerCodecs serverCodecs,
		final ApplicationInfoManager applicationInfoManager,
		final ReplicationClientAdditionalFilters replicationClientAdditionalFilters) {
	super(registry, serverConfig, clientConfig, serverCodecs,
			applicationInfoManager);
	this.replicationClientAdditionalFilters = replicationClientAdditionalFilters;
}
 
Example 30
@Bean
public PeerEurekaNodes myPeerEurekaNodes(PeerAwareInstanceRegistry registry,
		EurekaServerConfig eurekaServerConfig,
		EurekaClientConfig eurekaClientConfig, ServerCodecs serverCodecs,
		ApplicationInfoManager applicationInfoManager) {
	return new CustomEurekaPeerNodes(registry, eurekaServerConfig,
			eurekaClientConfig, serverCodecs, applicationInfoManager);
}