Java 类com.hazelcast.core.HazelcastInstance 实例源码

项目:greycat    文件:HazelcastScheduler.java   
public static void main(String[] args) {
    Config cfg = new Config();
    HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg);
    Map<Integer, String> mapCustomers = instance.getMap("customers");
    mapCustomers.put(1, "Joe");
    mapCustomers.put(2, "Ali");
    mapCustomers.put(3, "Avi");

    System.out.println("Customer with key 1: "+ mapCustomers.get(1));
    System.out.println("Map Size:" + mapCustomers.size());

    Queue<String> queueCustomers = instance.getQueue("customers");
    queueCustomers.offer("Tom");
    queueCustomers.offer("Mary");
    queueCustomers.offer("Jane");
    System.out.println("First customer: " + queueCustomers.poll());
    System.out.println("Second customer: "+ queueCustomers.peek());
    System.out.println("Queue size: " + queueCustomers.size());
}
项目:springboot-shiro-cas-mybatis    文件:HazelcastTicketRegistry.java   
/**
 * Instantiates a new Hazelcast ticket registry.
 *
 * @param hz                                   An instance of {@code HazelcastInstance}
 * @param mapName                              Name of map to use
 * @param ticketGrantingTicketTimeoutInSeconds TTL for TGT entries
 * @param serviceTicketTimeoutInSeconds        TTL for ST entries
 * @param pageSize                             the page size
 */
@Autowired
public HazelcastTicketRegistry(
    @Qualifier("hazelcast")
    final HazelcastInstance hz,
    @Value("${hz.mapname:tickets}")
    final String mapName,
    @Value("${tgt.maxTimeToLiveInSeconds:28800}")
    final long ticketGrantingTicketTimeoutInSeconds,
    @Value("${st.timeToKillInSeconds:10}")
    final long serviceTicketTimeoutInSeconds,
    @Value("${hz.page.size:500}")
    final int pageSize) {

    this.registry = hz.getMap(mapName);
    this.ticketGrantingTicketTimeoutInSeconds = ticketGrantingTicketTimeoutInSeconds;
    this.serviceTicketTimeoutInSeconds = serviceTicketTimeoutInSeconds;
    this.hz = hz;
    this.pageSize = pageSize;
}
项目:xm-commons    文件:XmConfigHazelcastConfiguration.java   
@Bean(TENANT_CONFIGURATION_HAZELCAST)
public HazelcastInstance tenantConfigurationHazelcast() throws IOException {
    log.info("{}", appProps.getHazelcast());

    Properties props = new Properties();
    props.putAll(appProps.getHazelcast());
    props.put(HAZELCAST_LOCAL_LOCAL_ADDRESS, InetUtils.getFirstNonLoopbackHostInfo().getIpAddress());

    String hazelcastConfigUrl = appProps.getHazelcast().get(HAZELCAST_CONFIG_URL_PROPERTY);
    InputStream in = context.getResource(hazelcastConfigUrl).getInputStream();

    Config config = new XmlConfigBuilder(in).setProperties(props).build();
    config.getNetworkConfig().setInterfaces(buildInterfaces(appProps.getHazelcast().get(INTERFACES)));
    HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(config);
    return hazelcastInstance;
}
项目:xm-ms-balance    文件:CacheConfiguration.java   
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("balance");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("balance");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.icthh.xm.ms.balance.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
项目:cas-5.1.0    文件:HazelcastSessionConfiguration.java   
/**
 * Hazelcast instance that is used by the spring session
 * repository to broadcast session events. The name
 * of this bean must be left untouched.
 *
 * @return the hazelcast instance
 */
@Bean
public HazelcastInstance hazelcastInstance() {
    final Resource hzConfigResource = casProperties.getWebflow().getSession().getHzLocation();
    try {
        final URL configUrl = hzConfigResource.getURL();
        final Config config = new XmlConfigBuilder(hzConfigResource.getInputStream()).build();
        config.setConfigurationUrl(configUrl);
        config.setInstanceName(this.getClass().getSimpleName())
                .setProperty("hazelcast.logging.type", "slf4j")
                .setProperty("hazelcast.max.no.heartbeat.seconds", "300");
        return Hazelcast.newHazelcastInstance(config);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
项目:testcontainers-hazelcast    文件:TestScratchpad.java   
public static void main(String[] args) {
    //System.setProperty("hazelcast.http.healthcheck.enabled", "true");
    final HazelcastInstance hazelcastInstance = newHazelcastInstance();

    HazelcastInstanceImpl hazelcastInstance1 = ((HazelcastInstanceProxy) hazelcastInstance).getOriginal();
    final InternalPartitionService partitionService = hazelcastInstance1.node.getPartitionService();

    boolean memberStateSafe = partitionService.isMemberStateSafe();
    System.out.println("memberStateSafe = " + memberStateSafe);
    boolean clusterSafe = memberStateSafe && !partitionService.hasOnGoingMigration();
    System.out.println("clusterSafe = " + clusterSafe);
    long migrationQueueSize = partitionService.getMigrationQueueSize();
    System.out.println("migrationQueueSize = " + migrationQueueSize);


}
项目:xm-ms-dashboard    文件:CacheConfiguration.java   
@Bean
@Primary
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("dashboard");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("dashboard");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.icthh.xm.ms.dashboard.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
项目:xm-gate    文件:CacheConfiguration.java   
@Bean
@Primary
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("gate");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("gate");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.icthh.xm.gate.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
项目:xm-ms-entity    文件:CacheConfiguration.java   
@Bean
@Primary
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("entity");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("entity");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.icthh.xm.ms.entity.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
项目:Code4Health-Platform    文件:CacheConfiguration.java   
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    Config config = new Config();
    config.setInstanceName("operoncloudplatform");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("cloud.operon.platform.domain.*", initializeDomainMapConfig(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
项目:cas-server-4.2.1    文件:HazelcastTicketRegistry.java   
/**
 * @param hz                                  An instance of {@code HazelcastInstance}
 * @param mapName                             Name of map to use
 * @param ticketGrantingTicketTimeoutInSeconds TTL for TGT entries
 * @param serviceTicketTimeoutInSeconds       TTL for ST entries
 */
@Autowired
public HazelcastTicketRegistry(
    @Qualifier("hazelcast")
    final HazelcastInstance hz,
    @Value("${hz.mapname:tickets}")
    final String mapName,
    @Value("${tgt.maxTimeToLiveInSeconds:28800}")
    final long ticketGrantingTicketTimeoutInSeconds,
    @Value("${st.timeToKillInSeconds:10}")
    final long serviceTicketTimeoutInSeconds) {

    this.registry = hz.getMap(mapName);
    this.ticketGrantingTicketTimeoutInSeconds = ticketGrantingTicketTimeoutInSeconds;
    this.serviceTicketTimeoutInSeconds = serviceTicketTimeoutInSeconds;
    this.hz = hz;
}
项目:cyp2sql    文件:KeyValueTest.java   
/**
 * Main method for executing the schema conversion to Hazelcast.
 * The method just needs to be called statically as it operates on files created during the initial
 * schema conversion process.
 */
public static void executeSchemaChange() {
    Config cfg = new Config();
    HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg);

    mapNodes = instance.getMap("nodes");
    mapEdges = instance.getMap("edges");
    mapLabels = instance.getMap("labels");
    mapOut = instance.getMap("out");
    mapIn = instance.getMap("in");

    nodesMap();
    edgesMap();

    exampleQueries();
}
项目:xm-ms-config    文件:TestConfiguration.java   
@Bean
@Primary
@SneakyThrows
public JGitRepository jGitRepository(ApplicationProperties applicationProperties, HazelcastInstance hazelcastInstance) {

    return new JGitRepository(applicationProperties.getGit(), new ReentrantLock()) {
        @Override
        protected void initRepository(){};
        @Override
        protected void pull(){};
        @Override
        protected void commitAndPush(String commitMsg){};
        @Override
        public List<com.icthh.xm.ms.configuration.domain.Configuration> findAll(){
            return emptyList();
        }
    };
}
项目:xm-ms-config    文件:LocalJGitRespotioryConfiguration.java   
@Bean
@Primary
@SneakyThrows
public JGitRepository jGitRepository(ApplicationProperties applicationProperties, HazelcastInstance hazelcastInstance) {
    File tmpDir = createTmpDir("work");
    tmpDir.mkdirs();

    ApplicationProperties.GitProperties gitProps = new ApplicationProperties.GitProperties();
    gitProps.setMaxWaitTimeSecond(30);

    final Git git = Git.init().setBare(false).setDirectory(tmpDir).call();

    return new JGitRepository(gitProps, new ReentrantLock()) {
        @Override
        protected void initRepository(){};
        @Override
        protected void pull(){};
        @Override
        protected void commitAndPush(String commitMsg){};
    };
}
项目:chili-core    文件:HazelMap.java   
/**
 * Initializes a new hazel async map.
 *
 * @param context the context requesting the map to be created.
 * @param future  called when the map is created.
 */
public HazelMap(Future<AsyncStorage> future, StorageContext<Value> context) {
    this.context = context;

    context.vertx().sharedData().<String, Value>getClusterWideMap(context.database(), cluster -> {
        if (cluster.succeeded()) {
            this.map = cluster.result();

            Optional<HazelcastInstance> hazel = Hazelcast.getAllHazelcastInstances().stream().findFirst();

            if (hazel.isPresent()) {
                HazelcastInstance instance = hazel.get();
                imap = instance.getMap(context.database());
                addIndex(Storable.idField);
                future.complete(this);
            } else {
                future.fail(CoreStrings.ERROR_NOT_CLUSTERED);
            }
        } else {
            future.fail(cluster.cause());
        }
    });
}
项目:spring-boot-concourse    文件:CacheAutoConfigurationTests.java   
@Test
public void hazelcastCacheWithMainHazelcastAutoConfigurationAndSeparateCacheConfig()
        throws IOException {
    String mainConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml";
    String cacheConfig = "org/springframework/boot/autoconfigure/cache/hazelcast-specific.xml";
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    EnvironmentTestUtils.addEnvironment(applicationContext,
            "spring.cache.type=hazelcast",
            "spring.cache.hazelcast.config=" + cacheConfig,
            "spring.hazelcast.config=" + mainConfig);
    applicationContext.register(DefaultCacheConfiguration.class);
    applicationContext.register(HazelcastAndCacheConfiguration.class);
    applicationContext.refresh();
    this.context = applicationContext;
    HazelcastInstance hazelcastInstance = this.context
            .getBean(HazelcastInstance.class);
    HazelcastCacheManager cacheManager = validateCacheManager(
            HazelcastCacheManager.class);
    HazelcastInstance cacheHazelcastInstance = (HazelcastInstance) new DirectFieldAccessor(
            cacheManager).getPropertyValue("hazelcastInstance");
    assertThat(cacheHazelcastInstance).isNotEqualTo(hazelcastInstance); // Our custom
    assertThat(hazelcastInstance.getConfig().getConfigurationFile())
            .isEqualTo(new ClassPathResource(mainConfig).getFile());
    assertThat(cacheHazelcastInstance.getConfig().getConfigurationFile())
            .isEqualTo(new ClassPathResource(cacheConfig).getFile());
}
项目:hazelcast-hibernate5    文件:HazelcastQueryResultsRegionTest.java   
@Before
public void setUp() throws Exception {
    mapConfig = mock(MapConfig.class);
    when(mapConfig.getMaxSizeConfig()).thenReturn(new MaxSizeConfig(maxSize, MaxSizeConfig.MaxSizePolicy.PER_NODE));
    when(mapConfig.getTimeToLiveSeconds()).thenReturn(timeout);

    config = mock(Config.class);
    when(config.findMapConfig(eq(REGION_NAME))).thenReturn(mapConfig);

    Cluster cluster = mock(Cluster.class);
    when(cluster.getClusterTime()).thenAnswer(new Answer<Long>() {
        @Override
        public Long answer(InvocationOnMock invocation) throws Throwable {
            return System.currentTimeMillis();
        }
    });

    instance = mock(HazelcastInstance.class);
    when(instance.getConfig()).thenReturn(config);
    when(instance.getCluster()).thenReturn(cluster);

    region = new HazelcastQueryResultsRegion(instance, REGION_NAME, new Properties());
}
项目:hazelcast-zookeeper    文件:HazelcastIntegrationTest.java   
@Test
public void testIntegration_urlNotConfigured() {
    exception.expect(IllegalStateException.class);
    exception.expectMessage("Zookeeper URL cannot be null.");

    Config config = new Config();
    config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
    config.setProperty("hazelcast.discovery.enabled", "true");

    DiscoveryStrategyConfig discoveryStrategyConfig = new DiscoveryStrategyConfig(new ZookeeperDiscoveryStrategyFactory());
    config.getNetworkConfig().getJoin().getDiscoveryConfig().addDiscoveryStrategyConfig(discoveryStrategyConfig);

    HazelcastInstance instance1 = Hazelcast.newHazelcastInstance(config);
    HazelcastInstance instance2 = Hazelcast.newHazelcastInstance(config);

    int instance1Size = instance1.getCluster().getMembers().size();
    assertEquals(2, instance1Size);
    int instance2Size = instance2.getCluster().getMembers().size();
    assertEquals(2, instance2Size);
}
项目:hazelcast-demo    文件:ListenerDemo.java   
public static void main(String[] args) {
    HazelcastInstance ins = Hazelcast.newHazelcastInstance();
    IMap<Integer, String> map = ins.getMap("");
    map.addEntryListener(new ListenerExample(), true);//添加自定义监听器
    map.put(1, "Grand Theft Auto");
    map.put(1, "Final Fantasy");
    map.put(2, "World Of Warcraft");

    HazelcastInstance insex = Hazelcast.newHazelcastInstance();
    IMap<Integer, String> mapex = insex.getMap("");

    System.out.println(mapex.get(1));
    System.out.println(mapex.get(2));
    mapex.remove(1);
    mapex.remove(2);
    System.exit(0);
}
项目:hazelcast-hibernate    文件:CustomPropertiesTest.java   
@Test
public void testNamedInstance() {
    TestHazelcastFactory factory = new TestHazelcastFactory();
    Config config = new Config();
    config.setInstanceName("hibernate");
    HazelcastInstance hz = factory.newHazelcastInstance(config);
    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.put(CacheEnvironment.HAZELCAST_INSTANCE_NAME, "hibernate");
    props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    assertTrue(hz.equals(HazelcastAccessor.getHazelcastInstance(sf)));
    sf.close();
    assertTrue(hz.getLifecycleService().isRunning());
    factory.shutdownAll();
}
项目:hazelcast-eureka    文件:HazelcastClientTestCase.java   
@Test
public void testSimpleDiscovery(){
    ArgumentCaptor<InstanceInfo> captor = ArgumentCaptor.forClass(InstanceInfo.class);

    EurekaHttpResponse<Applications> response = generateMockResponse(Collections.<InstanceInfo>emptyList());
    when(requestHandler.getApplications()).thenReturn(response);

    HazelcastInstance hz1 = factory.newHazelcastInstance();
    HazelcastInstance hz2 = factory.newHazelcastInstance();

    verify(requestHandler, timeout(5000).times(2)).register(captor.capture());
    response = generateMockResponse(captor.getAllValues());
    when(requestHandler.getApplications()).thenReturn(response);

    assertClusterSizeEventually(2, hz1);
    assertClusterSizeEventually(2, hz2);

    HazelcastInstance client = factory.newHazelcastClient();
    reset(requestHandler);
    when(requestHandler.getApplications()).thenReturn(response);
    verify(requestHandler, timeout(1000).times(0)).register(Matchers.<InstanceInfo>any());
    assertClusterSizeEventually(2, client);
}
项目:hazelcast-tomcat-sessionmanager    文件:AbstractStickySessionsTest.java   
@Test(timeout = 80000)
public void testFailover() throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    String value = executeRequest("read", SERVER_PORT_1, cookieStore);
    assertEquals("null", value);

    executeRequest("write", SERVER_PORT_1, cookieStore);

    instance1.stop();

    HazelcastInstance hzInstance1 = Hazelcast.getHazelcastInstanceByName("hzInstance1");
    if (hzInstance1 != null) {
        hzInstance1.shutdown();
    }

    value = executeRequest("read", SERVER_PORT_2, cookieStore);
    assertEquals("value", value);
}
项目:hazelcast-eureka    文件:HazelcastClientTestCase.java   
@Test
public void testInstanceRegistrationUsingProvidedEurekaClient() {
    EurekaClient eurekaClient = mock(EurekaClient.class);
    ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class);
    EurekaInstanceConfig eurekaInstanceConfig = mock(EurekaInstanceConfig.class);

    when(eurekaClient.getApplicationInfoManager()).thenReturn(applicationInfoManager);
    when(eurekaClient.getApplication(anyString())).thenReturn(new Application(APP_NAME));

    when(applicationInfoManager.getEurekaInstanceConfig()).thenReturn(eurekaInstanceConfig);
    when(eurekaInstanceConfig.getAppname()).thenReturn(APP_NAME);

    // use provided EurekaClient
    EurekaOneDiscoveryStrategyFactory.setEurekaClient(eurekaClient);

    HazelcastInstance hz1 = factory.newHazelcastInstance();
    HazelcastInstance hz2 = factory.newHazelcastInstance();

    verify(eurekaClient, times(2)).getApplicationInfoManager();
    verify(eurekaClient, times(2)).getApplication(APP_NAME);
    verify(applicationInfoManager, never()).setInstanceStatus(InstanceStatus.UP);
    verify(applicationInfoManager, never()).setInstanceStatus(any(InstanceStatus.class));

    assertClusterSizeEventually(2, hz1);
    assertClusterSizeEventually(2, hz2);
}
项目:hazelcast-hibernate    文件:CustomPropertiesTest.java   
@Test
public void testNamedInstance() {
    TestHazelcastFactory factory = new TestHazelcastFactory();
    Config config = new Config();
    config.setInstanceName("hibernate");
    HazelcastInstance hz = factory.newHazelcastInstance(config);
    Properties props = new Properties();
    props.setProperty(Environment.CACHE_REGION_FACTORY, HazelcastCacheRegionFactory.class.getName());
    props.put(CacheEnvironment.HAZELCAST_INSTANCE_NAME, "hibernate");
    props.put(CacheEnvironment.SHUTDOWN_ON_STOP, "false");
    props.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

    Configuration configuration = new Configuration();
    configuration.addProperties(props);

    SessionFactory sf = configuration.buildSessionFactory();
    assertTrue(hz.equals(HazelcastAccessor.getHazelcastInstance(sf)));
    sf.close();
    assertTrue(hz.getLifecycleService().isRunning());
    factory.shutdownAll();
}
项目:hazelcast-hibernate    文件:HazelcastQueryResultsRegionTest.java   
@Before
public void setUp() throws Exception {
    mapConfig = mock(MapConfig.class);
    when(mapConfig.getMaxSizeConfig()).thenReturn(new MaxSizeConfig(maxSize, MaxSizeConfig.MaxSizePolicy.PER_NODE));
    when(mapConfig.getTimeToLiveSeconds()).thenReturn(timeout);

    config = mock(Config.class);
    when(config.findMapConfig(eq(REGION_NAME))).thenReturn(mapConfig);

    Cluster cluster = mock(Cluster.class);
    when(cluster.getClusterTime()).thenAnswer(new Answer<Long>() {
        @Override
        public Long answer(InvocationOnMock invocation) throws Throwable {
            return System.currentTimeMillis();
        }
    });

    instance = mock(HazelcastInstance.class);
    when(instance.getConfig()).thenReturn(config);
    when(instance.getCluster()).thenReturn(cluster);

    region = new HazelcastQueryResultsRegion(instance, REGION_NAME, new Properties());
}
项目:subzero    文件:TestCustomerSerializers.java   
@Test
public void testGlobalCustomDelegateSerializationConfiguredProgrammaticallyForClientConfig() {
    Config memberConfig = new Config();
    SubZero.useAsGlobalSerializer(memberConfig);
    hazelcastFactory.newHazelcastInstance(memberConfig);

    String mapName = randomMapName();
    ClientConfig config = new ClientConfig();

    SubZero.useAsGlobalSerializer(config, MyGlobalDelegateSerlizationConfig.class);

    HazelcastInstance member = hazelcastFactory.newHazelcastClient(config);
    IMap<Integer, AnotherNonSerializableObject> myMap = member.getMap(mapName);
    myMap.put(0, new AnotherNonSerializableObject());
    AnotherNonSerializableObject fromCache = myMap.get(0);

    assertEquals("deserialized", fromCache.name);
}
项目:hazelcast-hibernate    文件:HibernateSerializationHookAvailableTest.java   
@Test
public void testAutoregistrationOnHibernate4Available()
        throws Exception {

    HazelcastInstance hz = Hazelcast.newHazelcastInstance();
    HazelcastInstanceImpl impl = (HazelcastInstanceImpl) ORIGINAL.get(hz);
    SerializationService ss = impl.getSerializationService();
    ConcurrentMap<Class, ?> typeMap = (ConcurrentMap<Class, ?>) TYPE_MAP.get(ss);

    boolean cacheKeySerializerFound = false;
    boolean cacheEntrySerializerFound = false;
    for (Class clazz : typeMap.keySet()) {
        if (clazz == CacheKey.class) {
            cacheKeySerializerFound = true;
        } else if (clazz == CacheEntry.class) {
            cacheEntrySerializerFound = true;
        }
    }

    assertTrue("CacheKey serializer not found", cacheKeySerializerFound);
    assertTrue("CacheEntry serializer not found", cacheEntrySerializerFound);
}
项目:hazelcast-wm    文件:AbstractWebFilterTest.java   
public ContainerContext(AbstractWebFilterTest test,
                        String serverXml1,
                        String serverXml2,
                        int serverPort1,
                        int serverPort2,
                        ServletContainer server1,
                        ServletContainer server2,
                        HazelcastInstance hz) {
    this.test = test;
    this.serverXml1 = serverXml1;
    this.serverXml2 = serverXml2;
    this.serverPort1 = serverPort1;
    this.serverPort2 = serverPort2;
    this.server1 = server1;
    this.server2 = server2;
    this.hz = hz;
}
项目:hazelcast-hibernate5    文件:HazelcastTimestampsRegionTest.java   
@Before
public void setUp() throws Exception {
    mapConfig = mock(MapConfig.class);
    when(mapConfig.getMaxSizeConfig()).thenReturn(new MaxSizeConfig(50, MaxSizeConfig.MaxSizePolicy.PER_NODE));
    when(mapConfig.getTimeToLiveSeconds()).thenReturn(timeout);

    config = mock(Config.class);
    when(config.findMapConfig(eq(REGION_NAME))).thenReturn(mapConfig);

    Cluster cluster = mock(Cluster.class);
    when(cluster.getClusterTime()).thenAnswer(new Answer<Long>() {
        @Override
        public Long answer(InvocationOnMock invocation) throws Throwable {
            return System.currentTimeMillis();
        }
    });

    instance = mock(HazelcastInstance.class);
    when(instance.getConfig()).thenReturn(config);
    when(instance.getCluster()).thenReturn(cluster);

    cache = mock(RegionCache.class);

    region = new HazelcastTimestampsRegion<RegionCache>(instance, REGION_NAME, new Properties(), cache);
}
项目:https-github.com-g0t4-jenkins2-course-spring-boot    文件:CacheAutoConfigurationTests.java   
@Test
public void hazelcastCacheWithMainHazelcastAutoConfiguration() throws IOException {
    String mainConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml";
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
    EnvironmentTestUtils.addEnvironment(applicationContext,
            "spring.cache.type=hazelcast", "spring.hazelcast.config=" + mainConfig);
    applicationContext.register(DefaultCacheConfiguration.class);
    applicationContext.register(HazelcastAndCacheConfiguration.class);
    applicationContext.refresh();
    this.context = applicationContext;
    HazelcastCacheManager cacheManager = validateCacheManager(
            HazelcastCacheManager.class);
    HazelcastInstance hazelcastInstance = this.context
            .getBean(HazelcastInstance.class);
    assertThat(getHazelcastInstance(cacheManager)).isEqualTo(hazelcastInstance);
    assertThat(hazelcastInstance.getConfig().getConfigurationFile())
            .isEqualTo(new ClassPathResource(mainConfig).getFile());
}
项目:spring-boot-concourse    文件:HazelcastAutoConfigurationTests.java   
@Test
public void configInstanceWithName() {
    Config config = new Config("my-test-instance");
    HazelcastInstance existingHazelcastInstance = Hazelcast
            .newHazelcastInstance(config);
    try {
        load(HazelcastConfigWithName.class,
                "spring.hazelcast.config=this-is-ignored.xml");
        HazelcastInstance hazelcastInstance = this.context
                .getBean(HazelcastInstance.class);
        assertThat(hazelcastInstance.getConfig().getInstanceName())
                .isEqualTo("my-test-instance");
        // Should reuse any existing instance by default.
        assertThat(hazelcastInstance).isEqualTo(existingHazelcastInstance);
    }
    finally {
        existingHazelcastInstance.shutdown();
    }
}
项目:hazelcast-jetty-sessionmanager    文件:JettySessionUtils.java   
/**
 * Create hazelcast full instance.
 *
 * @param configLocation the config location
 * @return the hazelcast instance
 */
public static HazelcastInstance createHazelcastFullInstance(String configLocation) {
    Config config;
    try {
        if (configLocation == null) {
            config = new XmlConfigBuilder().build();
        } else {
            config = ConfigLoader.load(configLocation);
        }
    } catch (IOException e) {
        throw new RuntimeException("failed to load config", e);
    }

    checkNotNull(config, "failed to find configLocation: " + configLocation);

    config.setInstanceName(DEFAULT_INSTANCE_NAME);
    return Hazelcast.getOrCreateHazelcastInstance(config);
}
项目:xm-uaa    文件:CacheConfiguration.java   
@Bean
public HazelcastInstance hazelcastInstance(JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Hazelcast");
    HazelcastInstance hazelCastInstance = Hazelcast.getHazelcastInstanceByName("uaa");
    if (hazelCastInstance != null) {
        log.debug("Hazelcast already initialized");
        return hazelCastInstance;
    }
    Config config = new Config();
    config.setInstanceName("uaa");
    config.getNetworkConfig().setPort(5701);
    config.getNetworkConfig().setPortAutoIncrement(true);

    // In development, remove multicast auto-configuration
    if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
        System.setProperty("hazelcast.local.localAddress", "127.0.0.1");

        config.getNetworkConfig().getJoin().getAwsConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(false);
    }
    config.getMapConfigs().put("default", initializeDefaultMapConfig());
    config.getMapConfigs().put("com.icthh.xm.uaa.domain.*", initializeDomainMapConfig(jHipsterProperties));
    // Uncomment if session needed
    //config.getMapConfigs().put("clustered-http-sessions", initializeClusteredSession(jHipsterProperties));
    return Hazelcast.newHazelcastInstance(config);
}
项目:greycat    文件:HazelcastTest.java   
public static void main(String[] args) {
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.addAddress("127.0.0.1:5701");
    HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
    IMap map = client.getMap("customers");
    System.out.println("Map Size:" + map.size());

    client.getDurableExecutorService("hello").submit(new HazelcastJob(() -> System.out.println("Hello")));

}
项目:springboot-shiro-cas-mybatis    文件:HazelcastTicketRegistry.java   
/**
 * @param hz An instance of <code>HazelcastInstance</code>
 * @param mapName Name of map to use
 * @param ticketGrantingTicketTimoutInSeconds TTL for TGT entries
 * @param serviceTicketTimeoutInSeconds TTL for ST entries
 */
public HazelcastTicketRegistry(final HazelcastInstance hz,
                               final String mapName,
                               final long ticketGrantingTicketTimoutInSeconds,
                               final long serviceTicketTimeoutInSeconds) {

    logInitialization(hz, mapName, ticketGrantingTicketTimoutInSeconds, serviceTicketTimeoutInSeconds);
    this.registry = hz.getMap(mapName);
    this.ticketGrantingTicketTimoutInSeconds = ticketGrantingTicketTimoutInSeconds;
    this.serviceTicketTimeoutInSeconds = serviceTicketTimeoutInSeconds;
    this.hz = hz;
}
项目:springboot-shiro-cas-mybatis    文件:HazelcastTicketRegistry.java   
/**
 * @param hz An instance of <code>HazelcastInstance</code>
 * @param mapName Name of map to use
 * @param ticketGrantingTicketTimoutInSeconds TTL for TGT entries
 * @param serviceTicketTimeoutInSeconds TTL for ST entries
 */
private void logInitialization(final HazelcastInstance hz,
                               final String mapName,
                               final long ticketGrantingTicketTimoutInSeconds,
                               final long serviceTicketTimeoutInSeconds) {

    logger.info("Setting up Hazelcast Ticket Registry...");
    logger.debug("Hazelcast instance: {}", hz);
    logger.debug("TGT timeout: [{}s]", ticketGrantingTicketTimoutInSeconds);
    logger.debug("ST timeout: [{}s]", serviceTicketTimeoutInSeconds);
}
项目:cas-5.1.0    文件:HazelcastMonitor.java   
@Override
protected CacheStatistics[] getStatistics() {
    final List<CacheStatistics> statsList = new ArrayList<>();
    final HazelcastProperties hz = casProperties.getTicket().getRegistry().getHazelcast();
    LOGGER.debug("Locating hazelcast instance [{}]...", hz.getCluster().getInstanceName());
    final HazelcastInstance instance = Hazelcast.getHazelcastInstanceByName(hz.getCluster().getInstanceName());

    instance.getConfig().getMapConfigs().keySet().forEach(key -> {
        final IMap map = instance.getMap(key);
        LOGGER.debug("Starting to collect hazelcast statistics for map [{}] identified by key [{}]...", map, key);
        statsList.add(new HazelcastStatistics(map, hz.getCluster().getMembers().size()));
    });
    return statsList.toArray(new CacheStatistics[statsList.size()]);
}
项目:cas-5.1.0    文件:HazelcastTicketRegistry.java   
/**
 * Instantiates a new Hazelcast ticket ticketGrantingTicketsRegistry.
 *
 * @param hz       An instance of {@code HazelcastInstance}
 * @param plan     the plan
 * @param pageSize the page size
 */
public HazelcastTicketRegistry(final HazelcastInstance hz, final TicketCatalog plan, final int pageSize) {
    this.hazelcastInstance = hz;
    this.pageSize = pageSize;
    this.ticketCatalog = plan;

    LOGGER.info("Setting up Hazelcast Ticket Registry instance [{}]", this.hazelcastInstance);
}
项目:teamcity-gradle-build-cache-plugin    文件:BuildCachePage.java   
public void fillModel(@NotNull Map<String, Object> model, @NotNull HttpServletRequest request) {
    HazelcastInstance instance = Hazelcast.getHazelcastInstanceByName(INSTANCE_NAME);
    if (instance != null) {
        IMap<String, byte[]> taskCache = instance.getMap(TASK_CACHE_NAME);
        LocalMapStats statistics = taskCache.getLocalMapStats();
        model.put("statistics", statistics);
    }
}
项目:testcontainers-hazelcast    文件:MongoMapStore.java   
@Override
public void init(HazelcastInstance hazelcastInstance, Properties properties, String mapName) {
    String mongoUrl = (String) properties.get("mongo.url");
    String dbName = (String) properties.get("mongo.db");
    String collectionName = (String) properties.get("mongo.collection");
    this.mongoClient = new MongoClient(new MongoClientURI(mongoUrl));
    this.collection = mongoClient.getDatabase(dbName).getCollection(collectionName);
}