com.hazelcast.config.Config

Here are the examples of the java api com.hazelcast.config.Config taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

111 Examples 7

19 Source : HazelcastAutoConfigurationTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void defaultConfigFile() {
    // no hazelcast-client.xml and hazelcast.xml is present in root clreplacedpath
    this.contextRunner.run((context) -> {
        Config config = context.getBean(HazelcastInstance.clreplaced).getConfig();
        replacedertThat(config.getConfigurationUrl()).isEqualTo(new ClreplacedPathResource("hazelcast.xml").getURL());
    });
}

19 Source : HazelcastAutoConfigurationServerTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void systemProperty() {
    this.contextRunner.withSystemProperties(HazelcastServerConfiguration.CONFIG_SYSTEM_PROPERTY + "=clreplacedpath:org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml").run((context) -> {
        Config config = context.getBean(HazelcastInstance.clreplaced).getConfig();
        replacedertThat(config.getQueueConfigs().keySet()).containsOnly("foobar");
    });
}

19 Source : HazelcastAutoConfigurationServerTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void explicitConfigUrl() {
    this.contextRunner.withPropertyValues("spring.hazelcast.config=hazelcast-default.xml").run((context) -> {
        Config config = context.getBean(HazelcastInstance.clreplaced).getConfig();
        replacedertThat(config.getConfigurationUrl()).isEqualTo(new ClreplacedPathResource("hazelcast-default.xml").getURL());
    });
}

19 Source : HazelcastAutoConfigurationServerTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void configInstanceWithName() {
    Config config = new Config("my-test-instance");
    HazelcastInstance existing = Hazelcast.newHazelcastInstance(config);
    try {
        this.contextRunner.withUserConfiguration(HazelcastConfigWithName.clreplaced).withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> {
            HazelcastInstance hazelcast = context.getBean(HazelcastInstance.clreplaced);
            replacedertThat(hazelcast.getConfig().getInstanceName()).isEqualTo("my-test-instance");
            // Should reuse any existing instance by default.
            replacedertThat(hazelcast).isEqualTo(existing);
        });
    } finally {
        existing.shutdown();
    }
}

19 Source : HazelcastAutoConfigurationServerTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void configInstanceWithoutName() {
    this.contextRunner.withUserConfiguration(HazelcastConfigNoName.clreplaced).withPropertyValues("spring.hazelcast.config=this-is-ignored.xml").run((context) -> {
        Config config = context.getBean(HazelcastInstance.clreplaced).getConfig();
        Map<String, QueueConfig> queueConfigs = config.getQueueConfigs();
        replacedertThat(queueConfigs.keySet()).containsOnly("another-queue");
    });
}

19 Source : HazelcastAutoConfigurationServerTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void defaultConfigFile() {
    // hazelcast.xml present in root clreplacedpath
    this.contextRunner.run((context) -> {
        Config config = context.getBean(HazelcastInstance.clreplaced).getConfig();
        replacedertThat(config.getConfigurationUrl()).isEqualTo(new ClreplacedPathResource("hazelcast.xml").getURL());
    });
}

19 Source : HazelcastAutoConfigurationServerTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void explicitConfigFile() {
    this.contextRunner.withPropertyValues("spring.hazelcast.config=org/springframework/boot/autoconfigure/hazelcast/" + "hazelcast-specific.xml").run((context) -> {
        Config config = context.getBean(HazelcastInstance.clreplaced).getConfig();
        replacedertThat(config.getConfigurationFile()).isEqualTo(new ClreplacedPathResource("org/springframework/boot/autoconfigure/hazelcast" + "/hazelcast-specific.xml").getFile());
    });
}

19 Source : HazelcastInstanceFactory.java
with Apache License 2.0
from yuanmabiji

/**
 * Factory that can be used to create a {@link HazelcastInstance}.
 *
 * @author Stephane Nicoll
 * @author Phillip Webb
 * @since 1.3.0
 */
public clreplaced HazelcastInstanceFactory {

    private final Config config;

    /**
     * Create a {@link HazelcastInstanceFactory} for the specified configuration location.
     * @param configLocation the location of the configuration file
     * @throws IOException if the configuration location could not be read
     */
    public HazelcastInstanceFactory(Resource configLocation) throws IOException {
        replacedert.notNull(configLocation, "ConfigLocation must not be null");
        this.config = getConfig(configLocation);
    }

    /**
     * Create a {@link HazelcastInstanceFactory} for the specified configuration.
     * @param config the configuration
     */
    public HazelcastInstanceFactory(Config config) {
        replacedert.notNull(config, "Config must not be null");
        this.config = config;
    }

    private Config getConfig(Resource configLocation) throws IOException {
        URL configUrl = configLocation.getURL();
        Config config = new XmlConfigBuilder(configUrl).build();
        if (ResourceUtils.isFileURL(configUrl)) {
            config.setConfigurationFile(configLocation.getFile());
        } else {
            config.setConfigurationUrl(configUrl);
        }
        return config;
    }

    /**
     * Get the {@link HazelcastInstance}.
     * @return the {@link HazelcastInstance}
     */
    public HazelcastInstance getHazelcastInstance() {
        if (StringUtils.hasText(this.config.getInstanceName())) {
            return Hazelcast.getOrCreateHazelcastInstance(this.config);
        }
        return Hazelcast.newHazelcastInstance(this.config);
    }
}

19 Source : ManualRunner.java
with Apache License 2.0
from XYUU

public static void main(String[] args) throws Exception {
    Config conf = new ClreplacedpathXmlConfig("hazelcast-consul-discovery-spi-example.xml");
    HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance(conf);
    Thread.currentThread().sleep(300000);
    System.exit(0);
}

19 Source : HazelcastManaged.java
with Apache License 2.0
from vgoldin

public static HazelcastInstance getInstance() {
    if (hazelcastInstance == null) {
        Config config = new XmlConfigBuilder().build();
        config.setInstanceName(Thread.currentThread().getName());
        hazelcastInstance = Hazelcast.getOrCreateHazelcastInstance(config);
    }
    return hazelcastInstance;
}

19 Source : HazelcastConfigurerAdapter.java
with GNU Lesser General Public License v2.1
from Verdoso

@Override
public void configure(Config config) {
// Noop. Override to add custom configuration.
}

19 Source : HazelcastConfig.java
with Apache License 2.0
from spring-avengers

@Bean
public Config config(DiscoveryServiceProvider discoveryServiceProvider) {
    Config config = new Config();
    config.getGroupConfig().setName(clusterName.toUpperCase());
    config.setProperty("hazelcast.discovery.enabled", Boolean.TRUE.toString());
    JoinConfig joinConfig = config.getNetworkConfig().getJoin();
    joinConfig.getMulticastConfig().setEnabled(false);
    joinConfig.getDiscoveryConfig().setDiscoveryServiceProvider(discoveryServiceProvider);
    config.getMapConfigs().put(CacheConstant.COMMINTING_GLOBALLOG_CACHE, new MapConfig(CacheConstant.COMMINTING_GLOBALLOG_CACHE).setBackupCount(2));
    config.getMapConfigs().put(CacheConstant.ROLLBACKING_GLOBALLOG_CACHE, new MapConfig(CacheConstant.ROLLBACKING_GLOBALLOG_CACHE).setBackupCount(2));
    Map<String, String> map = applicationInfoManager.getInfo().getMetadata();
    eurekaRegistration.getMetadata().put(HAZELCAST_VERSION_KEY, hazelcastVersion);
    eurekaRegistration.getMetadata().put(HAZELCAST_HOST_KEY, System.getProperty(HAZELCAST_HOST_KEY));
    eurekaRegistration.getMetadata().put(HAZELCAST_PORT_KEY, System.getProperty(HAZELCAST_PORT_KEY));
    map.putAll(eurekaRegistration.getMetadata());
    applicationInfoManager.registerAppMetadata(map);
    return config;
}

19 Source : CachetestassetApplication.java
with GNU Affero General Public License v3.0
from shiehn

@PostConstruct
public void LocalCache() {
    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("LOG: Customer with key 1: " + mapCustomers.get(1));
    System.out.println("LOG: Map Size:" + mapCustomers.size());
    Queue<String> queueCustomers = instance.getQueue("customers");
    queueCustomers.offer("Tom");
    queueCustomers.offer("Mary");
    queueCustomers.offer("Jane");
    System.out.println("LOG: First customer: " + queueCustomers.poll());
    System.out.println("LOG: Second customer: " + queueCustomers.peek());
    System.out.println("LOG: Queue size: " + queueCustomers.size());
}

19 Source : LocalCache.java
with GNU Affero General Public License v3.0
from shiehn

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");
    Application.logger.debug("LOG: Customer with key 1: " + mapCustomers.get(1));
    Application.logger.debug("LOG: Map Size:" + mapCustomers.size());
    Queue<String> queueCustomers = instance.getQueue("customers");
    queueCustomers.offer("Tom");
    queueCustomers.offer("Mary");
    queueCustomers.offer("Jane");
    Application.logger.debug("LOG: First customer: " + queueCustomers.poll());
    Application.logger.debug("LOG: Second customer: " + queueCustomers.peek());
    Application.logger.debug("LOG: Queue size: " + queueCustomers.size());
}

19 Source : Cluster.java
with BSD 3-Clause "New" or "Revised" License
from salesforce

/**
 * Initializes a Hazelcast cluster
 *   used for testing
 */
HazelcastInstance initHazelcast() throws FileNotFoundException {
    Config clusterConfig = new XmlConfigBuilder(loadResourceInsecure(hazelcastConfig.config())).build();
    return Hazelcast.newHazelcastInstance(clusterConfig);
}

19 Source : Application.java
with MIT License
from ralscha

@Bean
public Config hazelCastConfig() {
    Config config = new Config();
    config.setInstanceName("my-hazelcast-instance");
    return config;
}

19 Source : CachingConfig.java
with MIT License
from PacktPublishing

@Bean
public HazelcastInstance hazelcastInstance(Config hazelCastConfig) {
    return Hazelcast.newHazelcastInstance(hazelCastConfig);
}

19 Source : ServiceCacheConfiguration.java
with Apache License 2.0
from osswangxining

private void addZkConfig(Config config) {
    config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
    config.setProperty(GroupProperty.DISCOVERY_SPI_ENABLED.getName(), Boolean.TRUE.toString());
    DiscoveryStrategyConfig discoveryStrategyConfig = new DiscoveryStrategyConfig(new ZookeeperDiscoveryStrategyFactory());
    discoveryStrategyConfig.addProperty(ZookeeperDiscoveryProperties.ZOOKEEPER_URL.key(), zkUrl);
    discoveryStrategyConfig.addProperty(ZookeeperDiscoveryProperties.ZOOKEEPER_PATH.key(), zkDir);
    discoveryStrategyConfig.addProperty(ZookeeperDiscoveryProperties.GROUP.key(), HAZELCAST_CLUSTER_NAME);
    config.getNetworkConfig().getJoin().getDiscoveryConfig().addDiscoveryStrategyConfig(discoveryStrategyConfig);
}

19 Source : ServiceCacheConfiguration.java
with Apache License 2.0
from osswangxining

@Bean
public HazelcastInstance hazelcastInstance() {
    Config config = new Config();
    if (zkEnabled) {
        addZkConfig(config);
    }
    config.addMapConfig(createDeviceCredentialsCacheConfig());
    return Hazelcast.newHazelcastInstance(config);
}

19 Source : ThrottleCounterHazelcastImplTest.java
with Apache License 2.0
from OpenWiseSolutions

/**
 * Test suite for {@link ThrottleCounterMemoryImpl}.
 *
 * @author Petr Juza
 * @since 2.0
 */
public clreplaced ThrottleCounterHazelcastImplTest extends AbstractThrottleCounterTest {

    private Config config;

    @Before
    public void prepareConfig() throws IOException {
        Resource conf = new ClreplacedPathResource("config/ohf_hazelcast.xml");
        config = new Config();
        config.setConfigurationFile(conf.getFile());
    }

    @After
    public void shutdownHazelcast() {
        // gracefully shutdowns HazelcastInstance => necessary for running another tests
        Hazelcast.shutdownAll();
    }

    @Test
    public void testSingleNodeCounting() throws Exception {
        HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance(config);
        replacedertCounting(new ThrottleCounterHazelcastImpl(hazelcast));
    }

    @Test
    public void testTwoNodesCounting() throws Exception {
        HazelcastInstance hazelcast1 = Hazelcast.newHazelcastInstance(config);
        HazelcastInstance hazelcast2 = Hazelcast.newHazelcastInstance(config);
        ThrottleCounterHazelcastImpl counter1 = new ThrottleCounterHazelcastImpl(hazelcast1);
        ThrottleCounterHazelcastImpl counter2 = new ThrottleCounterHazelcastImpl(hazelcast2);
        replacedertCounting(counter1);
        // see replacedertCounting()
        ThrottleScope scope1 = new ThrottleScope("crm", "op1");
        int count = counter2.count(scope1, 10);
        replacedertThat(count, is(3));
    }

    @Test
    public void testMulreplacedhreadCountingWithSingleNode() throws Exception {
        HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance(config);
        replacedertMulreplacedhreadCounting(new ThrottleCounterHazelcastImpl(hazelcast));
    }

    @Test
    public void testMulreplacedhreadCountingWithTwoNodes() throws Exception {
        HazelcastInstance hazelcast1 = Hazelcast.newHazelcastInstance(config);
        HazelcastInstance hazelcast2 = Hazelcast.newHazelcastInstance(config);
        ThrottleCounterHazelcastImpl counter1 = new ThrottleCounterHazelcastImpl(hazelcast1);
        new ThrottleCounterHazelcastImpl(hazelcast2);
        new ThrottleCounterHazelcastImpl(Hazelcast.newHazelcastInstance(config));
        replacedertMulreplacedhreadCounting(counter1);
    }
}

19 Source : HazelcastTest.java
with Apache License 2.0
from opentracing-contrib

@BeforeClreplaced
public static void beforeClreplaced() {
    final Config config = new Config();
    config.setInstanceName("name");
    hazelcast = Hazelcast.newHazelcastInstance(config);
}

19 Source : HazelcastTest.java
with Apache License 2.0
from opentracing-contrib

@Test
public void testGetOrCreateHazelcastInstance(final MockTracer tracer) {
    final Config config = new Config();
    config.setInstanceName("name");
    test(Hazelcast.getOrCreateHazelcastInstance(config), tracer);
}

19 Source : TestBase64EncodedStateSet.java
with Apache License 2.0
from openlookeng

/**
 * set up before unit test run
 */
@BeforeSuite
private void setup() {
    Config config = new Config();
    config.setClusterName("cluster-test-encoded-set-" + UUID.randomUUID());
    // Specify ports to make sure different test cases won't connect to same cluster
    NetworkConfig network = config.getNetworkConfig();
    network.setPortAutoIncrement(false);
    network.setPort(PORT);
    hzInstance = Hazelcast.newHazelcastInstance(config);
}

19 Source : TestBase64EncodedStateMap.java
with Apache License 2.0
from openlookeng

/**
 * set up before unit test run
 */
@BeforeSuite
private void setup() {
    Config config = new Config();
    config.setClusterName("cluster-test-encoded-map-" + UUID.randomUUID());
    // Specify ports to make sure different test cases won't connect to same cluster
    NetworkConfig network = config.getNetworkConfig();
    network.setPortAutoIncrement(false);
    network.setPort(PORT);
    hzInstance = Hazelcast.newHazelcastInstance(config);
}

19 Source : TestHazelcastAuthenticationFailed.java
with Apache License 2.0
from openlookeng

@Test
public void testHazelcastAuthenticationFailed() {
    new KerberosConfigMockUp();
    Config config2 = new Config();
    config2.setClusterName(clusterName);
    NetworkConfig network2 = config2.getNetworkConfig();
    network2.setPortAutoIncrement(false);
    network2.setPort(PORT2);
    try {
        Hazelcast.newHazelcastInstance(config2);
        fail("The hazelcast instance should not join the cluster.");
    } catch (Exception e) {
        replacedertEquals(e.getMessage(), "Node failed to start!");
    }
}

19 Source : TestHazelcastAuthenticationFailed.java
with Apache License 2.0
from openlookeng

@BeforeSuite
public void setup() {
    KerberosConfig.setKerberosEnabled(true);
    new KerberosAuthenticatorMockUp();
    Config config1 = new Config();
    config1.setClusterName(clusterName);
    NetworkConfig network1 = config1.getNetworkConfig();
    network1.setPortAutoIncrement(false);
    network1.setPort(PORT1);
    config1.getSecurityConfig().setEnabled(true);
    hazelcastInstance = Hazelcast.newHazelcastInstance(config1);
}

19 Source : TestHazelcastAuthenticationDisabled.java
with Apache License 2.0
from openlookeng

@Test
public void testHazelcastAuthenticationDisabled() {
    String value1 = "aaa";
    String value2 = "bbb";
    Config config = new Config();
    HazelcastInstance hazelcastInstance1 = Hazelcast.newHazelcastInstance(config);
    Map<Integer, String> clusterMap1 = hazelcastInstance1.getMap("MyMap");
    clusterMap1.put(1, value1);
    HazelcastInstance hazelcastInstance2 = Hazelcast.newHazelcastInstance(config);
    Map<Integer, String> clusterMap2 = hazelcastInstance2.getMap("MyMap");
    clusterMap2.put(2, value2);
    replacedertEquals(clusterMap1.get(2), value2);
    replacedertEquals(clusterMap2.get(1), value1);
}

19 Source : TestHazelcastAuthenticationDisabled.java
with Apache License 2.0
from openlookeng

@BeforeSuite
public void setup() {
    String clusterName = "cluster-" + UUID.randomUUID();
    Config config1 = new Config();
    config1.setClusterName(clusterName);
    NetworkConfig network = config1.getNetworkConfig();
    network.setPortAutoIncrement(false);
    network.setPort(PORT1);
    hazelcastInstance1 = Hazelcast.newHazelcastInstance(config1);
    Config config2 = new Config();
    config2.setClusterName(clusterName);
    network = config2.getNetworkConfig();
    network.setPortAutoIncrement(false);
    network.setPort(PORT2);
    hazelcastInstance2 = Hazelcast.newHazelcastInstance(config2);
}

19 Source : HazelcastInstanceProvider.java
with ISC License
from mnemonic-no

private HazelcastInstance createInstance() {
    Config cfg = new Config(instanceName);
    cfg.getGroupConfig().setName(groupName);
    // Specify log4j2 to collect the Hazelcast logs together with the service logs (instead of stdout).
    cfg.setProperty("hazelcast.logging.type", "log4j2");
    // Disable Hazelcast's own shutdown hook because termination must be handle by the LifecycleAspect.
    cfg.setProperty("hazelcast.shutdownhook.enabled", "false");
    applyMulticastConfig(cfg);
    applySerializationConfig(cfg);
    applyQueueConfig(cfg);
    return Hazelcast.getOrCreateHazelcastInstance(cfg);
}

19 Source : HazelcastInstanceProvider.java
with ISC License
from mnemonic-no

private void applyQueueConfig(Config cfg) {
    // Configure the specifics of each Hazelcast queue.
    cfg.getQueueConfig(FACT_HAZELCAST_QUEUE_NAME).setBackupCount(1).setMaxSize(1_000);
}

19 Source : HazelcastInstanceProvider.java
with ISC License
from mnemonic-no

private void applyMulticastConfig(Config cfg) {
    cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(multicastEnabled).setMulticastGroup(multicastAddress).setMulticastPort(multicastPort);
}

19 Source : HazelcastLocal.java
with Apache License 2.0
from mini188

public synchronized HazelcastInstance getHazelcast() {
    if (hazelcast == null) {
        Config config = new ClreplacedpathXmlConfig("org/j2server/j2cache/cache/hazelcast/hazelcast-cache-config.xml");
        config.setInstanceName("j2cache");
        hazelcast = Hazelcast.newHazelcastInstance(config);
    }
    return hazelcast;
}

19 Source : HazelcastFactory.java
with Apache License 2.0
from micronaut-projects

/**
 * Create a singleton {@link HazelcastInstance} member, based on an existing {@link Config} bean.
 *
 * @param config the configuration read it as a bean
 * @return {@link HazelcastInstance}
 */
@Requires(beans = Config.clreplaced)
@Singleton
@Bean(preDestroy = "shutdown")
public HazelcastInstance hazelcastInstance(Config config) {
    return Hazelcast.newHazelcastInstance(config);
}

19 Source : HazelcastCacheMetricsCompatibilityTest.java
with Apache License 2.0
from micrometer-metrics

clreplaced HazelcastCacheMetricsCompatibilityTest extends CacheMeterBinderCompatibilityKit {

    private Config config = new Config();

    private IMap<String, String> cache = Hazelcast.newHazelcastInstance(config).getMap("mycache");

    @Disabled("This only demonstrates why we can't support miss count in Hazelcast.")
    @Issue("#586")
    @Test
    void multiInstanceMissCount() {
        IMap<String, String> cache2 = Hazelcast.newHazelcastInstance(config).getMap("mycache");
        // Since each member owns 1/N (N being the number of members in the cluster) entries of a distributed map,
        // we add two entries so we can deterministically say that each cache will "own" one entry.
        cache.put("k1", "v");
        cache.put("k2", "v");
        cache.get("k1");
        cache.get("k2");
        // cache stats: hits = 1, gets = 2, puts = 2
        // cache2 stats: hits = 1, gets = 0, puts = 0
        replacedertThat(cache.getLocalMapStats().getHits()).isEqualTo(1);
        replacedertThat(cache.getLocalMapStats().getGetOperationCount()).isEqualTo(2);
        replacedertThat(cache2.getLocalMapStats().getHits()).isEqualTo(1);
    // ... and this is why we can't calculate miss count in Hazelcast. sorry!
    }

    @AfterEach
    void cleanup() {
        Hazelcast.shutdownAll();
    }

    @Override
    public CacheMeterBinder binder() {
        return new HazelcastCacheMetrics(cache, emptyList());
    }

    @Override
    public void put(String key, String value) {
        cache.put(key, value);
    }

    @Override
    public String get(String key) {
        return cache.get(key);
    }
}

19 Source : HazelcastConfig.java
with GNU General Public License v3.0
from maithilish

/**
 * Get hazelcast server config.
 * @param fileName
 * @return
 */
public Config getConfig(final String fileName) {
    Config cfg = new XmlConfigBuilder(Cluster.clreplaced.getResourcereplacedtream(fileName)).build();
    cfg.setProperty("hazelcast.shutdownhook.policy", "GRACEFUL");
    return cfg;
}

19 Source : QuizExerciseDistributedCache.java
with MIT License
from ls1intum

static void registerSerializer(Config config) {
    SerializerConfig serializerConfig = new SerializerConfig();
    serializerConfig.setTypeClreplaced(QuizExerciseDistributedCache.clreplaced);
    serializerConfig.setImplementation(new QuizExerciseDistributedCacheStreamSerializer());
    config.getSerializationConfig().addSerializerConfig(serializerConfig);
}

19 Source : QuizExerciseCache.java
with MIT License
from ls1intum

static void registerSerializers(Config config) {
    QuizExerciseDistributedCache.registerSerializer(config);
}

19 Source : DistributedLockFactory.java
with GNU Affero General Public License v3.0
from KnowageLabs

public static void setDefaultConfig(Config config) {
    defaultConfig = config;
}

19 Source : InMemoryComponents.java
with Apache License 2.0
from klunge

@Bean
public Config config() {
    Config config = new Config();
    GroupConfig groupConfig = config.getGroupConfig();
    groupConfig.setName(hazelcastGrid);
    groupConfig.setPreplacedword(hazelcastPreplacedword);
    config.setGroupConfig(groupConfig);
    config.setInstanceName(artifactId);
    for (HazelcastConfigurer hazelcastConfigurer : hazelcastConfigurers) {
        config = hazelcastConfigurer.configure(config);
    }
    return config;
}

19 Source : UserCodeDeploymentConfig.java
with Apache License 2.0
from klunge

@Override
public Config configure(Config config) {
    config.setUserCodeDeploymentConfig(this);
    return config;
}

19 Source : NetworkInterfacesConfig.java
with Apache License 2.0
from klunge

@Override
public Config configure(Config config) {
    config.getNetworkConfig().setInterfaces(this);
    return config;
}

19 Source : MulticastConfig.java
with Apache License 2.0
from klunge

@Override
public Config configure(Config config) {
    config.getNetworkConfig().getJoin().setMulticastConfig(this);
    return config;
}

19 Source : MapsConfig.java
with Apache License 2.0
from klunge

@Override
public Config configure(Config config) {
    List<MapIndexConfig> indexes = Arrays.asList(new MapIndexConfig("startTime", true), new MapIndexConfig("operationState", true));
    config.getMapConfig(OPERATIONS_MAP_NAME).setTimeToLiveSeconds(OPERATIONS_MAX_TTL_INSEC).setMapIndexConfigs(indexes);
    config.getMapConfig(OPERATIONS_MAP_HISTORY_NAME).setMapIndexConfigs(indexes).setMaxSizeConfig(new MaxSizeConfig(evictFreePercentage, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_PERCENTAGE)).setEvictionPolicy(EvictionPolicy.LRU);
    config.getReplicatedMapConfig(TOPICS_MAP_NAME);
    config.getTopicConfig(OPERATIONS_TOPICS_NAME);
    return config;
}

19 Source : MapsConfig.java
with Apache License 2.0
from kloiasoft

@Override
public Config configure(Config config) {
    List<MapIndexConfig> indexes = Arrays.asList(new MapIndexConfig("startTime", true), new MapIndexConfig("operationState", true));
    config.getMapConfig(OPERATIONS_MAP_NAME).setTimeToLiveSeconds(OPERATIONS_MAX_TTL_INSEC).setMapIndexConfigs(indexes);
    config.getMapConfig(OPERATIONS_MAP_HISTORY_NAME).setMapIndexConfigs(indexes).setMaxSizeConfig(new MaxSizeConfig(evictFreePercentage, MaxSizeConfig.MaxSizePolicy.FREE_HEAP_PERCENTAGE)).setEvictionPolicy(EvictionPolicy.LRU);
    config.getReplicatedMapConfig(TOPICS_MAP_NAME);
    return config;
}

19 Source : BroadcastRegistry.java
with Apache License 2.0
from joyrpc

/**
 * hazelcast注册中心实现
 */
public clreplaced BroadcastRegistry extends AbstractRegistry {

    private static final Logger logger = LoggerFactory.getLogger(BroadcastRegistry.clreplaced);

    /**
     * 备份个数
     */
    public static final URLOption<Integer> BACKUP_COUNT = new URLOption<>("backupCount", 1);

    /**
     * 异步备份个数
     */
    public static final URLOption<Integer> ASYNC_BACKUP_COUNT = new URLOption<>("asyncBackupCount", 1);

    /**
     * hazelcast集群分组名称
     */
    public static final URLOption<String> BROADCAST_GROUP_NAME = new URLOption<>("broadCastGroupName", "development");

    /**
     * 节点广播端口
     */
    public static final URLOption<Integer> NETWORK_PORT = new URLOption<>("networkPort", 6701);

    /**
     * 节点广播端口递增个数
     */
    public static final URLOption<Integer> NETWORK_PORT_COUNT = new URLOption<>("networkPortCount", 100);

    /**
     * multicast分组
     */
    public static final URLOption<String> MULTICAST_GROUP = new URLOption<>("multicastGroup", Ipv4.isIpv4() ? "224.2.2.3" : "FF02:0:0:0:0:0:0:203");

    /**
     * multicast组播端口
     */
    public static final URLOption<Integer> MULTICAST_PORT = new URLOption<>("multicastPort", 64327);

    /**
     * multicast存活时间
     */
    public static final URLOption<Integer> MULTICAST_TIME_TO_LIVE = new URLOption<>("multicastTimeToLive", 32);

    /**
     * multicast超时时间
     */
    public static final URLOption<Integer> MULTICAST_TIMEOUT_SECONDS = new URLOption<>("multicastTimeoutSeconds", 2);

    /**
     * 节点失效时间参数
     */
    public static final URLOption<Long> NODE_EXPIRED_TIME = new URLOption<>("nodeExpiredTime", 30000L);

    /**
     * hazelcast实例配置
     */
    protected Config cfg;

    /**
     * 根路径
     */
    protected String root;

    /**
     * 节点时效时间, 至少 NODE_EXPIRED_TIME.getValue() ms
     */
    protected long nodeExpiredTime;

    /**
     * 存储provider的Map的路径函数
     */
    protected Function<URLKey, String> clusterPath;

    /**
     * 存在provider或者consumer的Map的路径函数
     */
    protected Function<URLKey, String> servicePath;

    /**
     * provider或consumer在存储map中的key值的函数
     */
    protected Function<URLKey, String> nodePath;

    /**
     * 存储接口配置的Map的路径函数
     */
    protected Function<URLKey, String> configPath;

    /**
     * 构造函数
     *
     * @param name   名称
     * @param url    url
     * @param backup 备份
     */
    public BroadcastRegistry(String name, URL url, Backup backup) {
        super(name, url, backup);
        this.cfg = new Config();
        int cpus = ENVIRONMENT.get().cpuCores() * 2;
        Properties properties = cfg.getProperties();
        properties.setProperty("hazelcast.operation.thread.count", String.valueOf(cpus));
        properties.setProperty("hazelcast.operation.generic.thread.count", String.valueOf(cpus));
        properties.setProperty("hazelcast.memcache.enabled", "false");
        properties.setProperty("hazelcast.rest.enabled", "false");
        // 从url里面获取hazelcast参数
        properties.putAll(url.startsWith("hazelcast."));
        // 不创建关闭钩子
        properties.setProperty("hazelcast.shutdownhook.enabled", "false");
        properties.setProperty("hazelcast.prefer.ipv4.stack", String.valueOf(Ipv4.isIpv4()));
        // 注册中心broadcast支持配置address,解决注册中心为broadcast时,因为网络环境隔离问题,hazelcast采用多播组网失败而导致服务发现失败。
        properties.setProperty("hazelcast.local.localAddress", url.getString("address", Ipv4.getLocalIp()));
        // 同步复制,可以读取从
        cfg.getMapConfig("default").setBackupCount(url.getPositiveInt(BACKUP_COUNT)).setAsyncBackupCount(url.getNaturalInt(ASYNC_BACKUP_COUNT)).setReadBackupData(false);
        cfg.setClusterName(url.getString(BROADCAST_GROUP_NAME));
        cfg.getNetworkConfig().setPort(url.getPositiveInt(NETWORK_PORT)).setPortCount(url.getInteger(NETWORK_PORT_COUNT));
        cfg.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(true).setMulticastGroup(url.getString(MULTICAST_GROUP)).setMulticastPort(url.getPositiveInt(MULTICAST_PORT)).setMulticastTimeToLive(url.getPositiveInt(MULTICAST_TIME_TO_LIVE)).setMulticastTimeoutSeconds(url.getPositiveInt(MULTICAST_TIMEOUT_SECONDS));
        this.nodeExpiredTime = Math.max(url.getLong(NODE_EXPIRED_TIME), NODE_EXPIRED_TIME.getValue());
        this.root = new RootPath().apply(url);
        this.clusterPath = new ClusterPath(root);
        this.servicePath = new ServicePath(root, false);
        this.nodePath = u -> u.getProtocol() + "://" + u.getHost() + ":" + u.getPort();
        this.configPath = new ConfigPath(root);
    }

    @Override
    protected Registion createRegistion(final URLKey key) {
        return new BroadcastRegistion(key, servicePath.apply(key), nodePath.apply(key));
    }

    @Override
    protected RegistryPilot create() {
        return new BroadcastController(this);
    }

    /**
     * 广播控制器
     */
    protected static clreplaced BroadcastController extends RegistryController<BroadcastRegistry> {

        /**
         * hazelcast实例
         */
        protected volatile HazelcastInstance instance;

        /**
         * 续约间隔
         */
        protected long leaseInterval;

        /**
         * 续约任务名称
         */
        protected String leaseTaskName;

        /**
         * 构造函数
         *
         * @param registry 注册中心
         */
        public BroadcastController(final BroadcastRegistry registry) {
            super(registry);
            this.leaseInterval = Math.max(15000, registry.nodeExpiredTime / 3);
            this.leaseTaskName = "Lease-" + registry.registryId;
        }

        @Override
        protected ClusterBooking createClusterBooking(final URLKey key) {
            return new BroadcastClusterBooking(key, this::dirty, getPublisher(key.getKey()), registry.clusterPath.apply(key));
        }

        @Override
        protected ConfigBooking createConfigBooking(final URLKey key) {
            return new BroadcastConfigBooking(key, this::dirty, getPublisher(key.getKey()), registry.configPath.apply(key));
        }

        @Override
        protected CompletableFuture<Void> doConnect() {
            return Futures.call(future -> {
                instance = Hazelcast.newHazelcastInstance(registry.cfg);
                future.complete(null);
            });
        }

        /**
         * 续约
         *
         * @param registion 注册
         */
        protected void lease(final BroadcastRegistion registion) {
            if (isOpen() && registers.containsKey(registion.getKey())) {
                try {
                    URL url = registion.getUrl();
                    IMap<String, URL> map = instance.getMap(registion.getPath());
                    // 续期
                    boolean isNotExpired = map.setTtl(registion.getNode(), registry.nodeExpiredTime, TimeUnit.MILLISECONDS);
                    // 节点已经过期,重新添加回节点,并修改meta的registerTime
                    if (!isNotExpired) {
                        map.putAsync(registion.getNode(), url, registry.nodeExpiredTime, TimeUnit.MILLISECONDS).whenComplete((u, e) -> {
                            if (e != null) {
                                if (!(e instanceof HazelcastInstanceNotActiveException)) {
                                    logger.error("Error occurs while leasing registion " + registion.getKey(), e);
                                }
                            } else {
                                registion.setRegisterTime(SystemClock.now());
                            }
                        });
                    }
                } catch (HazelcastInstanceNotActiveException e) {
                    logger.error("Error occurs while leasing registion " + registion.getKey() + ", caused by " + e.getMessage());
                } catch (Exception e) {
                    logger.error("Error occurs while leasing registion " + registion.getKey(), e);
                } finally {
                    if (isOpen() && registers.containsKey(registion.getKey())) {
                        timer().add(new Timer.DelegateTask(leaseTaskName, SystemClock.now() + registion.getLeaseInterval(), () -> lease(registion)));
                    }
                }
            }
        }

        @Override
        protected CompletableFuture<Void> doDisconnect() {
            if (instance != null) {
                instance.shutdown();
            }
            return super.doDisconnect();
        }

        @Override
        protected CompletableFuture<Void> doRegister(final Registion registion) {
            return Futures.call(future -> {
                BroadcastRegistion broadcastRegistion = (BroadcastRegistion) registion;
                IMap<String, URL> iMap = instance.getMap(broadcastRegistion.getPath());
                iMap.putAsync(broadcastRegistion.getNode(), registion.getUrl(), registry.nodeExpiredTime, TimeUnit.MILLISECONDS).whenComplete((u, e) -> {
                    if (e != null) {
                        if (isOpen()) {
                            logger.error(String.format("Error occurs while do register of %s, caused by %s", registion.getKey(), e.getMessage()));
                        }
                        future.completeExceptionally(e);
                    } else if (!isOpen()) {
                        future.completeExceptionally(new IllegalStateException("controller is closed."));
                    } else {
                        long interval = ThreadLocalRandom.current().nextLong(registry.nodeExpiredTime / 3, registry.nodeExpiredTime * 2 / 5);
                        interval = Math.max(15000, interval);
                        broadcastRegistion.setRegisterTime(SystemClock.now());
                        broadcastRegistion.setLeaseInterval(interval);
                        if (isOpen()) {
                            timer().add(new Timer.DelegateTask(leaseTaskName, SystemClock.now() + interval, () -> lease(broadcastRegistion)));
                        }
                        future.complete(null);
                    }
                });
            });
        }

        @Override
        protected CompletableFuture<Void> doDeregister(final Registion registion) {
            return Futures.call(future -> {
                String name = registry.servicePath.apply(registion);
                String key = registry.nodePath.apply(registion);
                IMap<String, URL> iMap = instance.getMap(name);
                iMap.removeAsync(key).whenComplete((u, e) -> {
                    if (e != null) {
                        future.completeExceptionally(e);
                    } else {
                        future.complete(null);
                    }
                });
            });
        }

        @Override
        protected CompletableFuture<Void> doSubscribe(final ClusterBooking booking) {
            return Futures.call(new Futures.Executor<Void>() {

                @Override
                public void execute(final CompletableFuture<Void> future) {
                    BroadcastClusterBooking broadcastBooking = (BroadcastClusterBooking) booking;
                    IMap<String, URL> map = instance.getMap(broadcastBooking.getPath());
                    List<ShardEvent> events = new LinkedList<>();
                    map.values().forEach(url -> events.add(new ShardEvent(new Shard.DefaultShard(url), ShardEventType.ADD)));
                    broadcastBooking.setListenerId(map.addEntryListener(broadcastBooking, true));
                    future.complete(null);
                    booking.handle(new ClusterEvent(booking, null, FULL, broadcastBooking.getStat().incrementAndGet(), events));
                }

                @Override
                public void onException(final Exception e) {
                    if (e instanceof HazelcastInstanceNotActiveException) {
                        logger.error(String.format("Error occurs while subscribe of %s, caused by %s", booking.getKey(), e.getMessage()));
                    } else {
                        logger.error(String.format("Error occurs while subscribe of %s, caused by %s", booking.getKey(), e.getMessage()), e);
                    }
                }
            });
        }

        @Override
        protected CompletableFuture<Void> doUnsubscribe(final ClusterBooking booking) {
            return Futures.call(future -> {
                BroadcastClusterBooking broadcastBooking = (BroadcastClusterBooking) booking;
                UUID listenerId = broadcastBooking.getListenerId();
                if (listenerId != null) {
                    IMap<String, URL> map = instance.getMap(broadcastBooking.getPath());
                    map.removeEntryListener(listenerId);
                }
                future.complete(null);
            });
        }

        @Override
        protected CompletableFuture<Void> doSubscribe(ConfigBooking booking) {
            return Futures.call(new Futures.Executor<Void>() {

                @Override
                public void execute(final CompletableFuture<Void> future) {
                    BroadcastConfigBooking broadcastBooking = (BroadcastConfigBooking) booking;
                    IMap<String, String> imap = instance.getMap(broadcastBooking.getPath());
                    Map<String, String> map = new HashMap<>(imap);
                    broadcastBooking.setListenerId(imap.addEntryListener(broadcastBooking, true));
                    future.complete(null);
                    booking.handle(new ConfigEvent(booking, null, broadcastBooking.getStat().incrementAndGet(), map));
                }

                @Override
                public void onException(final Exception e) {
                    if (e instanceof HazelcastInstanceNotActiveException) {
                        logger.error(String.format("Error occurs while subscribe of %s, caused by %s", booking.getKey(), e.getMessage()));
                    } else {
                        logger.error(String.format("Error occurs while subscribe of %s, caused by %s", booking.getKey(), e.getMessage()), e);
                    }
                }
            });
        }

        @Override
        protected CompletableFuture<Void> doUnsubscribe(final ConfigBooking booking) {
            return Futures.call(future -> {
                BroadcastConfigBooking broadcastBooking = (BroadcastConfigBooking) booking;
                UUID listenerId = broadcastBooking.getListenerId();
                if (listenerId != null) {
                    IMap<String, URL> map = instance.getMap(broadcastBooking.getPath());
                    map.removeEntryListener(listenerId);
                }
                future.complete(null);
            });
        }
    }

    /**
     * 广播注册
     */
    protected static clreplaced BroadcastRegistion extends Registion {

        /**
         * 注册时间
         */
        protected long registerTime;

        /**
         * 续约时间间隔
         */
        protected long leaseInterval;

        /**
         * 节点
         */
        protected String node;

        public BroadcastRegistion(final URLKey key, final String path, final String node) {
            super(key, path);
            this.node = node;
        }

        @Override
        public void close() {
            registerTime = 0;
            super.close();
        }

        public long getRegisterTime() {
            return registerTime;
        }

        public void setRegisterTime(long registerTime) {
            this.registerTime = registerTime;
        }

        public long getLeaseInterval() {
            return leaseInterval;
        }

        public void setLeaseInterval(long leaseInterval) {
            this.leaseInterval = leaseInterval;
        }

        public String getNode() {
            return node;
        }
    }

    /**
     * 广播集群订阅
     */
    protected static clreplaced BroadcastClusterBooking extends ClusterBooking implements EntryAddedListener<String, URL>, EntryUpdatedListener<String, URL>, EntryRemovedListener<String, URL>, EntryExpiredListener<String, URL> {

        /**
         * 计数器
         */
        protected AtomicLong stat = new AtomicLong(0);

        /**
         * 监听器ID
         */
        protected UUID listenerId;

        public BroadcastClusterBooking(final URLKey key, final Runnable dirty, final Publisher<ClusterEvent> publisher, final String path) {
            super(key, dirty, publisher, path);
            this.path = path;
        }

        @Override
        public void entryAdded(final EntryEvent<String, URL> event) {
            handle(new ClusterEvent(this, null, UPDATE, stat.incrementAndGet(), Collections.singletonList(new ShardEvent(new Shard.DefaultShard(event.getValue()), ShardEventType.ADD))));
        }

        @Override
        public void entryExpired(final EntryEvent<String, URL> event) {
            handle(new ClusterEvent(this, null, UPDATE, stat.incrementAndGet(), Collections.singletonList(new ShardEvent(new Shard.DefaultShard(event.getOldValue()), ShardEventType.DELETE))));
        }

        @Override
        public void entryRemoved(final EntryEvent<String, URL> event) {
            handle(new ClusterEvent(this, null, UPDATE, stat.incrementAndGet(), Collections.singletonList(new ShardEvent(new Shard.DefaultShard(event.getOldValue()), ShardEventType.DELETE))));
        }

        @Override
        public void entryUpdated(final EntryEvent<String, URL> event) {
            handle(new ClusterEvent(this, null, UPDATE, stat.incrementAndGet(), Collections.singletonList(new ShardEvent(new Shard.DefaultShard(event.getValue()), ShardEventType.UPDATE))));
        }

        public UUID getListenerId() {
            return listenerId;
        }

        public void setListenerId(UUID listenerId) {
            this.listenerId = listenerId;
        }

        public AtomicLong getStat() {
            return stat;
        }
    }

    /**
     * 广播配置订阅
     */
    protected static clreplaced BroadcastConfigBooking extends ConfigBooking implements EntryAddedListener<String, String>, EntryUpdatedListener<String, String>, EntryRemovedListener<String, String>, EntryExpiredListener<String, String> {

        /**
         * 计数器
         */
        protected AtomicLong stat = new AtomicLong(0);

        /**
         * 监听器ID
         */
        protected UUID listenerId;

        /**
         * 构造函数
         *
         * @param key       key
         * @param dirty     脏函数
         * @param publisher 发布器
         * @param path      配置路径
         */
        public BroadcastConfigBooking(final URLKey key, final Runnable dirty, final Publisher<ConfigEvent> publisher, final String path) {
            super(key, dirty, publisher, path);
        }

        @Override
        public void entryAdded(final EntryEvent<String, String> event) {
            Map<String, String> data = datum == null ? new HashMap<>() : new HashMap<>(datum);
            data.put(event.getKey(), event.getValue());
            handle(new ConfigEvent(this, null, stat.incrementAndGet(), data));
        }

        @Override
        public void entryExpired(final EntryEvent<String, String> event) {
            Map<String, String> data = datum == null ? new HashMap<>() : new HashMap<>(datum);
            data.remove(event.getKey());
            handle(new ConfigEvent(this, null, stat.incrementAndGet(), data));
        }

        @Override
        public void entryRemoved(final EntryEvent<String, String> event) {
            Map<String, String> data = datum == null ? new HashMap<>() : new HashMap<>(datum);
            data.remove(event.getKey());
            handle(new ConfigEvent(this, null, stat.incrementAndGet(), data));
        }

        @Override
        public void entryUpdated(final EntryEvent<String, String> event) {
            Map<String, String> data = datum == null ? new HashMap<>() : new HashMap<>(datum);
            data.put(event.getKey(), event.getValue());
            handle(new ConfigEvent(this, null, stat.incrementAndGet(), data));
        }

        public UUID getListenerId() {
            return listenerId;
        }

        public void setListenerId(UUID listenerId) {
            this.listenerId = listenerId;
        }

        public AtomicLong getStat() {
            return stat;
        }
    }
}

19 Source : HazelcastConfigTest.java
with Apache License 2.0
from jloisel

@Test
public void shouldAutowire() throws UnknownHostException {
    Config localhost = config.config(new HazelcastQuorumListener(1), "localhost");
    replacedertNotNull(localhost);
    localhost = config.config(new HazelcastQuorumListener(2), "localhost, 127.0.0.1");
    replacedertNotNull(localhost);
}

19 Source : HazelcastConfig.java
with Apache License 2.0
from jloisel

@Bean
Config config(final MembershipListener listener, @Value("${clustering.hazelcast.members:127.0.0.1}") final String members) throws UnknownHostException {
    final Config config = new Config();
    final NetworkConfig network = config.getNetworkConfig();
    final JoinConfig join = network.getJoin();
    final MulticastConfig multicast = join.getMulticastConfig();
    multicast.setEnabled(false);
    final TcpIpConfig tcpIp = join.getTcpIpConfig();
    tcpIp.setEnabled(true);
    for (final String member : COMA.splitToList(members)) {
        final InetAddress[] addresses = MoreObjects.firstNonNull(InetAddress.getAllByName(member), new InetAddress[0]);
        for (final InetAddress addr : addresses) {
            final String hostAddress = addr.getHostAddress();
            tcpIp.addMember(hostAddress);
            log.info("[Hazelcast] New Member: " + hostAddress);
        }
    }
    return config.addListenerConfig(new ListenerConfig(listener));
}

19 Source : SubZeroTest.java
with Apache License 2.0
from jerrinot

@Test
public void givenGlobalSerializerConfigDoesNotExist_whenUseAsGlobalSerializer_thenNewSubZeroIsUsedAsGlobalSerializer() {
    Config config = new Config();
    SubZero.useAsGlobalSerializer(config);
    replacedertEquals(Serializer.clreplaced.getName(), config.getSerializationConfig().getGlobalSerializerConfig().getClreplacedName());
}

19 Source : SubZeroTest.java
with Apache License 2.0
from jerrinot

@Test
public void useForClreplacedes() {
    Config config = new Config();
    SubZero.useForClreplacedes(config, String.clreplaced);
    Collection<SerializerConfig> serializerConfigs = config.getSerializationConfig().getSerializerConfigs();
    replacedertThat(serializerConfigs).extracting("typeClreplaced").contains(String.clreplaced);
}

19 Source : SubZeroTest.java
with Apache License 2.0
from jerrinot

@Test
public void givenGlobalSerializerConfigDoes_whenUseAsGlobalSerializer_thenNewSubZeroIsUsedAsGlobalSerializer() {
    Config config = new Config();
    config.getSerializationConfig().setGlobalSerializerConfig(new GlobalSerializerConfig().setClreplacedName("foo"));
    SubZero.useAsGlobalSerializer(config);
    replacedertEquals(Serializer.clreplaced.getName(), config.getSerializationConfig().getGlobalSerializerConfig().getClreplacedName());
}

See More Examples