Java源码示例:org.infinispan.client.hotrod.configuration.ConfigurationBuilder
示例1
public static void main(String[] args) {
// Create a configuration for a locally-running server
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
// Connect to the server
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
// Retrieve the cache containing the scripts
RemoteCache<String, String> scriptCache = cacheManager.getCache("___script_cache");
// Create a simple script which multiplies to numbers
scriptCache.put("simple.js", "multiplicand * multiplier");
// Obtain the remote cache
RemoteCache<String, Integer> cache = cacheManager.administration().getOrCreateCache("test", DefaultTemplate.DIST_SYNC);
// Create the parameters for script execution
Map<String, Object> params = new HashMap<>();
params.put("multiplicand", 10);
params.put("multiplier", 20);
// Run the script on the server, passing in the parameters
Object result = cache.execute("simple.js", params);
// Print the result
System.out.printf("Result = %s\n", result);
// Stop the cache manager and release resources
cacheManager.stop();
}
示例2
public static void main(String[] args) {
// Create a configuration for a locally-running server
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer()
.host("127.0.0.1")
.port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
.security().authentication()
//Add user credentials.
.username("username")
.password("password")
.realm("default")
.saslMechanism("DIGEST-MD5");
// Connect to the server
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
// Create test cache, if such does not exist
cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).getOrCreateCache("test", DefaultTemplate.DIST_SYNC);
// Obtain the remote cache
RemoteCache<String, String> cache = cacheManager.getCache("test");
/// Store a value
cache.put("key", "value");
// Retrieve the value and print it out
System.out.printf("key = %s\n", cache.get("key"));
// Stop the cache manager and release all resources
cacheManager.stop();
}
示例3
public static void main(String[] args) {
// Create a client configuration connecting to a local server
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
builder.nearCache().mode(NearCacheMode.INVALIDATED).maxEntries(20).cacheNamePattern("near-.*");
// Connect to the server
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
// Create one remote cache with near caching disabled and one with near caching enabled
RemoteCache<Integer, String> numbers = cacheManager.administration().getOrCreateCache("numbers", DefaultTemplate.DIST_SYNC);
RemoteCache<Integer, String> nearNumbers = cacheManager.administration().getOrCreateCache("near-numbers", DefaultTemplate.DIST_SYNC);
for (int i = 1; i<= 20; i++) {
numbers.put(i, String.valueOf(i));
nearNumbers.put(i, String.valueOf(i));
}
// Read both caches data
readCache(numbers);
readCache(nearNumbers);
// Stop the cache manager and release all resources
cacheManager.stop();
}
示例4
@Override
public void startVendorInstance() throws Exception {
String workerType = get("WORKER_TYPE");
if ("javaclient".equals(workerType)) {
Properties hotrodProperties = new Properties();
hotrodProperties.setProperty("infinispan.client.hotrod.server_list", get("server_list"));
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder().withProperties(hotrodProperties);
Configuration configuration = configurationBuilder.build();
RemoteCacheManager remoteCacheManager = new RemoteCacheManager(configuration);
this.cacheContainer = remoteCacheManager;
} else {
DefaultCacheManager defaultCacheManager = new DefaultCacheManager("infinispan.xml");
this.cacheContainer = defaultCacheManager;
HotRodServerConfiguration hotRodServerConfiguration = new HotRodServerConfigurationBuilder()
.host(get("PRIVATE_ADDRESS")).port(11222).build();
this.hotRodServer = new HotRodServer();
hotRodServer.start(hotRodServerConfiguration, defaultCacheManager);
}
}
示例5
@Override
public void startVendorInstance() throws Exception {
String workerType = get("WORKER_TYPE");
if ("javaclient".equals(workerType)) {
Properties hotrodProperties = new Properties();
hotrodProperties.setProperty("infinispan.client.hotrod.server_list", get("server_list"));
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder().withProperties(hotrodProperties);
Configuration configuration = configurationBuilder.build();
RemoteCacheManager remoteCacheManager = new RemoteCacheManager(configuration);
this.cacheContainer = remoteCacheManager;
} else {
DefaultCacheManager defaultCacheManager = new DefaultCacheManager("infinispan.xml");
this.cacheContainer = defaultCacheManager;
HotRodServerConfiguration hotRodServerConfiguration = new HotRodServerConfigurationBuilder()
.host(get("PRIVATE_ADDRESS")).port(11222).build();
this.hotRodServer = new HotRodServer();
hotRodServer.start(hotRodServerConfiguration, defaultCacheManager);
}
}
示例6
@Override
protected void initialize(Properties properties, String host, int port, String username, String password, String cacheName) {
String realm = property(properties, "search.realm", "default");
String serverName = property(properties, "search.server-name", "infinispan");
ClientIntelligence ci = ClientIntelligence.valueOf(property(properties, "search.client-intelligence", "BASIC"));
ConfigurationBuilder clientBuilder = new ConfigurationBuilder();
clientBuilder
.addServer().host(host).port(port)
.security().authentication().username(username).password(password).realm(realm).serverName(serverName)
.clientIntelligence(ci)
.marshaller(new ProtoStreamMarshaller());
manager = new RemoteCacheManager(clientBuilder.build());
}
示例7
private static RemoteCacheManager raw() {
ConfigurationBuilder clientBuilder = new ConfigurationBuilder();
clientBuilder.addServer()
.host("localhost")
.port(11222)
.security()
.authentication().username("user").password("pass").realm("default").serverName("infinispan")
.clientIntelligence(ClientIntelligence.BASIC);
return new RemoteCacheManager(clientBuilder.build());
}
示例8
@Test
public void testBasicFlow() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder
.addServer()
.host("127.0.0.1")
.port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
.security()
.authentication()
.username("admin")
.password("admin")
.realm("default")
.serverName("infinispan")
.saslMechanism("DIGEST-MD5")
.clientIntelligence(ClientIntelligence.BASIC);
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
BpmnProcess process = (BpmnProcess) BpmnProcess.from(new ClassPathResource("BPMN2-UserTask.bpmn2")).get(0);
process.setProcessInstancesFactory(new CacheProcessInstancesFactory(cacheManager));
process.configure();
ProcessInstance<BpmnVariables> processInstance = process.createInstance(BpmnVariables.create(Collections.singletonMap("test", "test")));
processInstance.start();
assertEquals(STATE_ACTIVE, processInstance.status());
SecurityPolicy asJohn = SecurityPolicy.of(new StaticIdentityProvider("john"));
WorkItem workItem = processInstance.workItems(asJohn).get(0);
assertNotNull(workItem);
assertEquals("john", workItem.getParameters().get("ActorId"));
processInstance.completeWorkItem(workItem.getId(), null, asJohn);
assertEquals(STATE_COMPLETED, processInstance.status());
}
示例9
@Bean
public org.infinispan.client.hotrod.configuration.Configuration customConfiguration() {
return new ConfigurationBuilder()
.addServers("127.0.0.1:6667")
.tcpNoDelay(false)
.tcpKeepAlive(true)
.build();
}
示例10
@PostConstruct
public void start() throws Exception {
var config = new ConfigurationBuilder()
.addServer()
.host(this.properties.getHost())
.port(this.properties.getPort());
if (this.properties.isUseTls()) {
config.security()
.ssl()
.enable()
.sniHostName(sniHostName(this.properties.getHost()))
.trustStorePath(this.properties.getTrustStorePath());
}
if (this.properties.getUsername() != null) {
config
.security()
.authentication()
.realm(this.properties.getSaslRealm())
.serverName(this.properties.getSaslServerName())
.username(this.properties.getUsername())
.password(this.properties.getPassword());
}
customizeServerConfiguration(config);
this.remoteCacheManager = new RemoteCacheManager(config.build());
}
示例11
public static void main(String[] args) {
// Create a configuration for a locally-running server
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer()
.host("127.0.0.1")
.port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
.security().authentication()
//Add user credentials.
.username("username")
.password("password")
.realm("default")
.saslMechanism("DIGEST-MD5");
//Add per-cache configuration that uses an org.infinispan cache template.
builder.remoteCache("my-cache")
.templateName("org.infinispan.DIST_SYNC");
//Add per-cache configuration with a cache definition in XML format.
builder.remoteCache("another-cache")
.configuration("<infinispan><cache-container><distributed-cache name=\"another-cache\"><encoding media-type=\"application/x-protostream\"/></distributed-cache></cache-container></infinispan>");
// Connect to the server
try (RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build())) {
// Obtain a remote cache that does not exist.
// Rather than return null, create the cache from a template.
RemoteCache<String, String> cache = cacheManager.getCache("my-cache");
/// Store a value
cache.put("hello", "world");
// Retrieve the value and print it out
System.out.printf("key = %s\n", cache.get("hello"));
}
}
示例12
private static RemoteCache<String,String> getExecCache() {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(11222);
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
return cacheManager.administration()
.withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
.getOrCreateCache("data", DefaultTemplate.DIST_SYNC);
}
示例13
private InfinispanRemoteAdminCache() {
// Create a configuration for a locally running server.
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer()
.host("127.0.0.1")
.port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
.security().authentication()
//Add user credentials.
.username("username")
.password("password")
.realm("default")
.saslMechanism("DIGEST-MD5");
manager = new RemoteCacheManager(builder.build());
}
示例14
public static void main(String[] args) throws InterruptedException {
// Create a configuration for a locally-running server
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer()
.host("127.0.0.1")
.port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
.security().authentication()
//Add user credentials.
.username("username")
.password("password")
.realm("default")
.saslMechanism("DIGEST-MD5");
// Connect to the server
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
// Get the cache, create it if needed with an existing template name
RemoteCache<String, String> cache = cacheManager.administration()
.withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
.getOrCreateCache("listen", DefaultTemplate.DIST_SYNC);
// Register a listener
MyListener listener = new MyListener();
cache.addClientListener(listener);
// Store some values
cache.put("key1", "value1");
cache.put("key2", "value2");
cache.put("key1", "newValue");
// Remote events are asynchronous, so wait a bit
Thread.sleep(1000);
// Remove listener
cache.removeClientListener(listener);
// Stop the cache manager and release all resources
cacheManager.stop();
}
示例15
public static void main(String[] args) {
// Create a configuration for a locally-running server
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer().host("127.0.0.1").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
// Workaround for docker 4 mac
builder.clientIntelligence(ClientIntelligence.BASIC);
//Configure the security properties
builder.security().authentication()
.username("Titus Bramble")
.password("Shambles")
.saslMechanism("DIGEST-MD5")
.realm("default")
.serverName("infinispan");
// Connect to the server
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
// Create test cache, if such does not exist
cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).getOrCreateCache("test",
DefaultTemplate.DIST_SYNC);
// Obtain the remote cache
RemoteCache<String, String> cache = cacheManager.getCache("test");
/// Store a value
cache.put("key", "value");
// Retrieve the value and print it out
System.out.printf("key = %s\n", cache.get("key"));
// Stop the cache manager and release all resources
cacheManager.stop();
}
示例16
public static void main(String[] args) throws Exception {
// Create a configuration for a locally-running server
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer()
.host("127.0.0.1")
.port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
.security().authentication()
//Add user credentials.
.username("username")
.password("password")
.realm("default")
.saslMechanism("DIGEST-MD5");
// Connect to the server and create a cache
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
// Create people cache if needed with an existing template name
cacheManager.administration()
.withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
.getOrCreateCache(PEOPLE_MULTIMAP, DefaultTemplate.DIST_SYNC);
// Retrieve the MultimapCacheManager from the CacheManager.
MultimapCacheManager multimapCacheManager = RemoteMultimapCacheManagerFactory.from(cacheManager);
// Retrieve the multimap cache.
RemoteMultimapCache<Integer, String> people = multimapCacheManager.get(PEOPLE_MULTIMAP);
people.put(2016, "Alberto");
people.put(2016, "Oihana");
people.put(2016, "Roman");
people.put(2016, "Ane");
people.put(2017, "Paula");
people.put(2017, "Aimar");
people.put(2018, "Elaia");
people.get(2016).whenComplete((v, ex) -> {
System.out.println(v);
}).join();
// Stop the cache manager and release all resources
cacheManager.stop();
}
示例17
public void boot() throws Exception {
Properties props = new Properties();
// list of urls for the infinispan server
// as we run in domain node we have two servers out of the box, and can therefore include both
// that the client can load balance/failover to be highly available
props.setProperty("infinispan.client.hotrod.server_list", "localhost:11222;localhost:11372");
// by default, previously existing values for java.util.Map operations
// are not returned for remote caches but they are required for the route
// policy to work.
props.setProperty("infinispan.client.hotrod.force_return_values", "true");
// create remote infinispan cache manager and start it
RemoteCacheManager remote = new RemoteCacheManager(
new ConfigurationBuilder().withProperties(props).build(),
true
);
// setup Camel infinispan configuration to use the remote cache manager
InfinispanConfiguration ic = new InfinispanConfiguration();
ic.setCacheContainer(remote);
// setup the hazelcast route policy
InfinispanRoutePolicy routePolicy = new InfinispanRoutePolicy(ic);
// the lock names must be same in the foo and bar server
routePolicy.setLockMapName("myLock");
routePolicy.setLockKey("myLockKey");
// the lock value identifies the node
routePolicy.setLockValue("foo");
main = new Main();
// bind the hazelcast route policy to the name myPolicy which we refer to from the route
main.bind("myPolicy", routePolicy);
// add the route and and let the route be named Bar and use a little delay when processing the files
main.addRouteBuilder(new FileConsumerRoute("Foo", 100));
main.run();
}
示例18
public void boot() throws Exception {
Properties props = new Properties();
// list of urls for the infinispan server
// as we run in domain node we have two servers out of the box, and can therefore include both
// that the client can load balance/failover to be highly available
props.setProperty("infinispan.client.hotrod.server_list", "localhost:11222;localhost:11372");
// by default, previously existing values for java.util.Map operations
// are not returned for remote caches but they are required for the route
// policy to work.
props.setProperty("infinispan.client.hotrod.force_return_values", "true");
// create remote infinispan cache manager and start it
RemoteCacheManager remote = new RemoteCacheManager(
new ConfigurationBuilder().withProperties(props).build(),
true
);
// setup Camel infinispan configuration to use the remote cache manager
InfinispanConfiguration ic = new InfinispanConfiguration();
ic.setCacheContainer(remote);
// setup the hazelcast route policy
InfinispanRoutePolicy routePolicy = new InfinispanRoutePolicy(ic);
// the lock names must be same in the foo and bar server
routePolicy.setLockMapName("myLock");
routePolicy.setLockKey("myLockKey");
// the lock value identifies the node
routePolicy.setLockValue("bar");
main = new Main();
// bind the hazelcast route policy to the name myPolicy which we refer to from the route
main.bind("myPolicy", routePolicy);
// add the route and and let the route be named Bar and use a little delay when processing the files
main.addRouteBuilder(new FileConsumerRoute("Bar", 100));
main.run();
}
示例19
/**
* 초기화 함수, 설정파일을 읽어서 캐시를 초기화한다.
*
* @param configFile
* @param cacheName
* @param loginCacheName
* @throws IOException
*/
@Override
public void initialize(String configFile, String cacheName, String loginCacheName)
throws IOException {
StringUtils.isNotNull("configFile", configFile);
Configuration configuration = null;
ConfigurationBuilder builder = new ConfigurationBuilder();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
builder.classLoader(cl);
InputStream stream = cl.getResourceAsStream(configFile);
if (stream == null) {
logger.error("Can't Found configFile=" + configFile);
} else {
try {
builder.withProperties(loadFromStream(stream));
} finally {
Util.close(stream);
}
}
configuration = builder.build();
cacheManager = new RemoteCacheManager(configuration);
cache = cacheManager.getCache(cacheName);
loginCache = cacheManager.getCache(loginCacheName);
waitForConnectionReady();
}
示例20
@Override
@Bean
public CacheManager cacheManager() {
return new SpringRemoteCacheManager(
new RemoteCacheManager(
new ConfigurationBuilder()
.addServer()
.host("localhost")
.build()
)
);
}
示例21
private void initialize() {
log.debug("Initializing CacheManager");
Configuration conf;
if (properties == null) {
// We already loaded and it wasn't present - so use an empty config
conf = new ConfigurationBuilder().build();
} else {
conf = builderFromProperties(properties).build();
}
cacheManager = new RemoteCacheManager(conf);
// TODO: do we want to automatically register all the proto file definitions?
RemoteCache<String, String> protobufMetadataCache = null;
Set<SerializationContextInitializer> initializers = (Set) properties.remove(PROTOBUF_INITIALIZERS);
if (initializers != null) {
for (SerializationContextInitializer initializer : initializers) {
if (protobufMetadataCache == null) {
protobufMetadataCache = cacheManager.getCache(
ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME);
}
protobufMetadataCache.put(initializer.getProtoFileName(), initializer.getProtoFile());
}
}
for (Map.Entry<Object, Object> property : properties.entrySet()) {
Object key = property.getKey();
if (key instanceof String) {
String keyString = (String) key;
if (keyString.startsWith(InfinispanClientProducer.PROTOBUF_FILE_PREFIX)) {
String fileName = keyString.substring(InfinispanClientProducer.PROTOBUF_FILE_PREFIX.length());
String fileContents = (String) property.getValue();
if (protobufMetadataCache == null) {
protobufMetadataCache = cacheManager.getCache(
ProtobufMetadataManagerConstants.PROTOBUF_METADATA_CACHE_NAME);
}
protobufMetadataCache.put(fileName, fileContents);
}
}
}
}
示例22
/**
* The mirror side of {@link #replaceProperties(Properties)} so that we can take out any objects that were
* instantiated during static init time and inject them properly
*
* @param properties the properties that was static constructed
* @return the configuration builder based on the provided properties
*/
private ConfigurationBuilder builderFromProperties(Properties properties) {
// If you are changing this method, you will most likely have to change replaceProperties as well
ConfigurationBuilder builder = new ConfigurationBuilder();
Object marshallerInstance = properties.remove(ConfigurationProperties.MARSHALLER);
if (marshallerInstance != null) {
if (marshallerInstance instanceof ProtoStreamMarshaller) {
handleProtoStreamMarshaller((ProtoStreamMarshaller) marshallerInstance, properties, beanManager);
}
builder.marshaller((Marshaller) marshallerInstance);
}
InfinispanClientRuntimeConfig infinispanClientRuntimeConfig = this.infinispanClientRuntimeConfig.get();
infinispanClientRuntimeConfig.serverList
.ifPresent(v -> properties.put(ConfigurationProperties.SERVER_LIST, v));
infinispanClientRuntimeConfig.clientIntelligence
.ifPresent(v -> properties.put(ConfigurationProperties.CLIENT_INTELLIGENCE, v));
infinispanClientRuntimeConfig.useAuth
.ifPresent(v -> properties.put(ConfigurationProperties.USE_AUTH, v));
infinispanClientRuntimeConfig.authUsername
.ifPresent(v -> properties.put(ConfigurationProperties.AUTH_USERNAME, v));
infinispanClientRuntimeConfig.authPassword
.ifPresent(v -> properties.put(ConfigurationProperties.AUTH_PASSWORD, v));
infinispanClientRuntimeConfig.authRealm
.ifPresent(v -> properties.put(ConfigurationProperties.AUTH_REALM, v));
infinispanClientRuntimeConfig.authServerName
.ifPresent(v -> properties.put(ConfigurationProperties.AUTH_SERVER_NAME, v));
infinispanClientRuntimeConfig.authClientSubject
.ifPresent(v -> properties.put(ConfigurationProperties.AUTH_CLIENT_SUBJECT, v));
infinispanClientRuntimeConfig.authCallbackHandler
.ifPresent(v -> properties.put(ConfigurationProperties.AUTH_CALLBACK_HANDLER, v));
infinispanClientRuntimeConfig.saslMechanism
.ifPresent(v -> properties.put(ConfigurationProperties.SASL_MECHANISM, v));
builder.withProperties(properties);
return builder;
}
示例23
public ConfigurationBuilder getConfigurationBuilder() {
ConfigurationBuilder builder = new ConfigurationBuilder();
Properties properties = this.getProperties();
builder.withProperties(properties);
return builder;
}
示例24
@Bean
@Conditional({ConditionalOnCacheType.class, ConditionalOnConfiguration.class})
@ConditionalOnMissingBean
@Qualifier(REMOTE_CACHE_MANAGER_BEAN_QUALIFIER)
public RemoteCacheManager remoteCacheManager() throws IOException {
boolean hasHotRodPropertiesFile = ctx.getResource(infinispanProperties.getClientProperties()).exists();
boolean hasConfigurer = infinispanRemoteConfigurer != null;
boolean hasProperties = StringUtils.hasText(infinispanProperties.getServerList());
ConfigurationBuilder builder;
if (hasConfigurer) {
org.infinispan.client.hotrod.configuration.Configuration configuration = infinispanRemoteConfigurer.getRemoteConfiguration();
Objects.nonNull(configuration);
builder = new ConfigurationBuilder().read(configuration);
cacheCustomizers.forEach(c -> c.customize(builder));
} else if (hasHotRodPropertiesFile) {
String remoteClientPropertiesLocation = infinispanProperties.getClientProperties();
Resource hotRodClientPropertiesFile = ctx.getResource(remoteClientPropertiesLocation);
Properties hotrodClientProperties = new Properties();
try (InputStream stream = hotRodClientPropertiesFile.getURL().openStream()) {
hotrodClientProperties.load(stream);
builder = new ConfigurationBuilder().withProperties(hotrodClientProperties);
cacheCustomizers.forEach(c -> c.customize(builder));
}
} else if (hasProperties) {
builder = infinispanProperties.getConfigurationBuilder();
cacheCustomizers.forEach(c -> c.customize(builder));
} else if (infinispanConfiguration != null) {
builder = new ConfigurationBuilder().read(infinispanConfiguration);
cacheCustomizers.forEach(c -> c.customize(builder));
} else {
throw new IllegalStateException("Not enough data to create RemoteCacheManager. Check InfinispanRemoteCacheManagerChecker" +
"and update conditions.");
}
org.infinispan.client.hotrod.configuration.Configuration config = builder.build();
List<String> whiteList = new ArrayList<>(config.serialWhitelist());
whiteList.forEach(builder::addJavaSerialWhiteList);
builder.addJavaSerialWhiteList("java.util.*", "java.time.*", "org.springframework.*", "org.infinispan.spring.common.*", "org.infinispan.spring.remote.*");
builder.marshaller(new JavaSerializationMarshaller());
return new RemoteCacheManager(builder.build());
}
示例25
@Bean
public InfinispanRemoteConfigurer infinispanRemoteConfigurer() {
return () -> new ConfigurationBuilder().statistics().disable().addServer().host("127.0.0.1").port(PORT).build();
}
示例26
@Bean
public InfinispanRemoteConfigurer configuration() {
return () -> new ConfigurationBuilder()
.addServers(serverList)
.build();
}
示例27
public static void main(String[] args) throws Exception {
// Create a configuration for a locally-running server
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer()
.host("127.0.0.1")
.port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
.security().authentication()
//Add user credentials.
.username("username")
.password("password")
.realm("default")
.saslMechanism("DIGEST-MD5");
// Configure the RemoteCacheManager to use a transactional cache as default
// Use the simple TransactionManager in hot rod client
builder.transaction().transactionManagerLookup(RemoteTransactionManagerLookup.getInstance());
// The cache will be enlisted as Synchronization
builder.transaction().transactionMode(TransactionMode.NON_XA);
// Connect to the server
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
// Create a transactional cache in the server since there is none available by default.
cacheManager.administration().createCache(CACHE_NAME, new XMLStringConfiguration(TEST_CACHE_XML_CONFIG));
RemoteCache<String, String> cache = cacheManager.getCache(CACHE_NAME);
// Obtain the transaction manager
TransactionManager transactionManager = cache.getTransactionManager();
// Perform some operations within a transaction and commit it
transactionManager.begin();
cache.put("key1", "value1");
cache.put("key2", "value2");
transactionManager.commit();
// Display the current cache contents
System.out.printf("key1 = %s\nkey2 = %s\n", cache.get("key1"), cache.get("key2"));
// Perform some operations within a transaction and roll it back
transactionManager.begin();
cache.put("key1", "value3");
cache.put("key2", "value4");
transactionManager.rollback();
// Display the current cache contents
System.out.printf("key1 = %s\nkey2 = %s\n", cache.get("key1"), cache.get("key2"));
// Stop the cache manager and release all resources
cacheManager.stop();
}
示例28
public static void main(String[] args) throws UnknownHostException {
// Obtain the Infinispan address
String infinispanAddress = args[0];
// Adjust log levels
Logger.getLogger("org").setLevel(Level.WARN);
// Create the remote cache manager
Configuration build = new ConfigurationBuilder().addServer().host(infinispanAddress).build();
RemoteCacheManager remoteCacheManager = new RemoteCacheManager(build);
// Obtain the remote cache
RemoteCache<Integer, Temperature> cache = remoteCacheManager.getCache();
// Add some data
cache.put(1, new Temperature(21, "London"));
cache.put(2, new Temperature(34, "Rome"));
cache.put(3, new Temperature(33, "Barcelona"));
cache.put(4, new Temperature(8, "Oslo"));
// Create java spark context
SparkConf conf = new SparkConf().setAppName("infinispan-spark-simple-job");
JavaSparkContext jsc = new JavaSparkContext(conf);
// Create InfinispanRDD
ConnectorConfiguration config = new ConnectorConfiguration().setServerList(infinispanAddress);
JavaPairRDD<Integer, Temperature> infinispanRDD = InfinispanJavaRDD.createInfinispanRDD(jsc, config);
// Convert RDD to RDD of doubles
JavaDoubleRDD javaDoubleRDD = infinispanRDD.values().mapToDouble(Temperature::getValue);
// Calculate average temperature
Double meanTemp = javaDoubleRDD.mean();
System.out.printf("\nAVERAGE TEMPERATURE: %f C\n", meanTemp);
// Calculate standard deviation
Double stdDev = javaDoubleRDD.sampleStdev();
System.out.printf("STD DEVIATION: %f C\n ", stdDev);
// Calculate histogram of temperatures
System.out.println("TEMPERATURE HISTOGRAM:");
double[] buckets = {0d, 10d, 20d, 30d, 40d};
long[] histogram = javaDoubleRDD.histogram(buckets);
for (int i = 0; i < buckets.length - 1; i++) {
System.out.printf("Between %f C and %f C: %d cities\n", buckets[i], buckets[i + 1], histogram[i]);
}
}
示例29
public static void main(String[] args) throws Exception {
// Create a configuration for a locally-running server
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer()
.host("127.0.0.1")
.port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
.security().authentication()
//Add user credentials.
.username("username")
.password("password")
.realm("default")
.saslMechanism("DIGEST-MD5");
// Connect to the server
RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());
// Retrieve the CounterManager from the CacheManager. Each CacheManager has it own CounterManager
CounterManager counterManager = RemoteCounterManagerFactory.asCounterManager(cacheManager);
// Create 3 counters.
// The first counter is bounded to 10 (upper-bound).
counterManager.defineCounter("counter-1", CounterConfiguration.builder(CounterType.BOUNDED_STRONG)
.upperBound(10)
.initialValue(1)
.build());
// The second counter is unbounded
counterManager.defineCounter("counter-2", CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG)
.initialValue(2)
.build());
// And finally, the third counter is a weak counter.
counterManager.defineCounter("counter-3", CounterConfiguration.builder(CounterType.WEAK)
.initialValue(3)
.build());
// StrongCounter provides the higher consistency. Its value is known during the increment/decrement and it may be bounded.
// Bounded counters are aimed for uses cases where a limit is needed.
StrongCounter counter1 = counterManager.getStrongCounter("counter-1");
// All methods returns a CompletableFuture. So you can do other work while the counter value is being computed.
counter1.getValue().thenAccept(value -> System.out.println("Counter-1 initial value is " + value)).get();
// Try to add more than the upper-bound
counter1.addAndGet(10).handle((value, throwable) -> {
// Value is null since the counter is bounded and we can add 10 to it.
System.out.println("Counter-1 Exception is " + throwable.getMessage());
return 0;
}).get();
// Check the counter value. It should be the upper-bound (10)
counter1.getValue().thenAccept(value -> System.out.println("Counter-1 value is " + value)).get();
//Decrement the value. Should be 9.
counter1.decrementAndGet().handle((value, throwable) -> {
// No exception this time.
System.out.println("Counter-1 new value is " + value);
return value;
}).get();
// Similar to counter-1, counter-2 is a strong counter but it is unbounded. It will never throw the CounterOutOfBoundsException
StrongCounter counter2 = counterManager.getStrongCounter("counter-2");
// All counters allow a listener to be registered.
// The handle can be used to remove the listener
counter2.addListener(event -> System.out
.println("Counter-2 event: oldValue=" + event.getOldValue() + " newValue=" + event.getNewValue()));
// Adding MAX_VALUE won't throws an exception. But the all the increments won't have any effect since we can store
//any value larger the MAX_VALUE
counter2.addAndGet(Long.MAX_VALUE).thenAccept(aLong -> System.out.println("Counter-2 value is " + aLong)).get();
// Conditional operations are allowed in strong counters
counter2.compareAndSet(Long.MAX_VALUE, 0)
.thenAccept(aBoolean -> System.out.println("Counter-2 CAS result is " + aBoolean)).get();
counter2.getValue().thenAccept(value -> System.out.println("Counter-2 value is " + value)).get();
// Reset the counter to its initial value (2)
counter2.reset().get();
counter2.getValue().thenAccept(value -> System.out.println("Counter-2 initial value is " + value)).get();
// Retrieve counter-3
WeakCounter counter3 = counterManager.getWeakCounter("counter-3");
// Weak counter doesn't have its value available during updates. This makes the increment faster than the StrongCounter
// Its value is computed lazily and stored locally.
// Its main use case is for uses-case where faster increments are needed.
counter3.add(5).thenAccept(aVoid -> System.out.println("Adding 5 to counter-3 completed!")).get();
// Check the counter value.
System.out.println("Counter-3 value is " + counter3.getValue());
// Stop the cache manager and release all resources
cacheManager.stop();
}
示例30
public static void main(String[] args) throws Exception {
// Create a configuration for a locally-running server
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.addServer()
.host("127.0.0.1")
.port(ConfigurationProperties.DEFAULT_HOTROD_PORT)
.security().authentication()
//Add user credentials.
.username("username")
.password("password")
.realm("default")
.saslMechanism("DIGEST-MD5");
// Connect to the server
RemoteCacheManager client = new RemoteCacheManager(builder.build());
// Get the people cache, create it if needed with the default configuration
RemoteCache<String, Person> peopleCache = client.administration()
.withFlags(CacheContainerAdmin.AdminFlag.VOLATILE)
.getOrCreateCache("people-remote-query", DefaultTemplate.DIST_SYNC);
// Create the persons dataset to be stored in the cache
Map<String, Person> people = new HashMap<>();
people.put("1", new Person("Oihana", "Rossignol", 2016, "Paris"));
people.put("2", new Person("Elaia", "Rossignol", 2018, "Paris"));
people.put("3", new Person("Yago", "Steiner", 2013, "Saint-Mandé"));
people.put("4", new Person("Alberto", "Steiner", 2016, "Paris"));
// Create and add the Protobuf schema for Person class. Note Person is an annotated POJO
addPersonSchema(client);
// Put all the values in the cache
peopleCache.putAll(people);
// Get a query factory from the cache
QueryFactory queryFactory = Search.getQueryFactory(peopleCache);
// Create a query with lastName parameter
Query query = queryFactory.create("FROM tutorial.Person p where p.lastName = :lastName");
// Set the parameter value
query.setParameter("lastName", "Rossignol");
// Execute the query
List<Person> rossignols = query.list();
// Print the results
System.out.println(rossignols);
// Stop the client and release all resources
client.stop();
}