can't run a couchbase cluster with more than one node - amazon-ec2

I trying Couchbase. I wrote some code (with the help of couchbase documentation). Reading and writing work very fine when I have 1 server.
When I put a 2nd server, I can't write/or read... Connection is very long (it was blazing fast with 1 server)
What am I doing wrong ?
The code is clearly working. This is something I do when I add a node on EC2 ? All ports are open (to the entire world). When I joined the cluster, rebalancing was ok.
Example: my cluster is up and running (here with 5 nodes on EC2):
Here is my log :
Connection:
2014-07-04 17:25:20.600 INFO net.spy.memcached.auth.AuthThread: Authenticated to /54.247.158.182:11210
2014-07-04 17:25:20.811 INFO com.couchbase.client.vbucket.provider.BucketConfigurationProvider: Could bootstrap through carrier publication.
write:
2014-07-04 17:25:20.817 INFO com.couchbase.client.CouchbaseConnection: Added {QA sa=/10.57.35.15:11210, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
2014-07-04 17:25:20.818 INFO com.couchbase.client.CouchbaseConnection: Added {QA sa=/10.250.110.205:11210, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
2014-07-04 17:25:20.818 INFO com.couchbase.client.CouchbaseConnection: Added {QA sa=/10.250.153.230:11210, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
2014-07-04 17:25:20.819 INFO com.couchbase.client.CouchbaseConnection: Added {QA sa=/10.59.13.200:11210, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
2014-07-04 17:25:20.819 INFO com.couchbase.client.CouchbaseConnection: Added {QA sa=/10.65.51.132:11210, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
read:
2014-07-04 17:25:30.820 INFO com.couchbase.client.vbucket.provider.BucketConfigurationProvider: Could bootstrap through carrier publication.
2014-07-04 17:25:45.847 INFO com.couchbase.client.CouchbaseClient: CouchbaseConnectionFactory{bucket='Users', nodes=[http://54.247.158.182:8091/pools], order=RANDOM, opTimeout=2500, opQueue=16384, opQueueBlockTime=10000, obsPollInt=10, obsPollMax=500, obsTimeout=5000, viewConns=10, viewTimeout=75000, viewWorkers=1, configCheck=10, reconnectInt=1100, failureMode=Redistribute, hashAlgo=NATIVE_HASH, authWaitTime=2500}
Connected to CouchbaseConnectionFactory{bucket='Users', nodes=[http://54.247.158.182:8091/pools], order=RANDOM, opTimeout=2500, opQueue=16384, opQueueBlockTime=10000, obsPollInt=10, obsPollMax=500, obsTimeout=5000, viewConns=10, viewTimeout=75000, viewWorkers=1, configCheck=10, reconnectInt=1100, failureMode=Redistribute, hashAlgo=NATIVE_HASH, authWaitTime=2500}
2014-07-04 17:26:10.908 INFO com.couchbase.client.CouchbaseClient: viewmode property isn't defined. Setting viewmode to production mode
2014-07-04 17:26:10.989 INFO com.couchbase.client.CouchbaseConnection: Node for key "user101" is not active (yet). Queueing up for retry and checking for stale configuration.
2014-07-04 17:26:11.362 INFO com.couchbase.client.CouchbaseConnection: Node for key "user101" is not active (yet). Queueing up for retry and checking for stale configuration.
2014-07-04 17:26:12.363 INFO com.couchbase.client.CouchbaseConnection: Node for key "user101" is not active (yet). Queueing up for retry and checking for stale configuration.
2014-07-04 17:26:13.365 INFO com.couchbase.client.CouchbaseConnection: Node for key "user101" is not active (yet). Queueing up for retry and checking for stale configuration.
2014-07-04 17:26:13.490 WARN net.spy.memcached.MemcachedConnection: handling node for operation is not set
java.lang.RuntimeException: Timed out waiting for operation
at net.spy.memcached.internal.OperationFuture.get(OperationFuture.java:142)
at com.t2s.injector.Injector.insertData(Injector.java:71)
at com.t2s.injector.Injector.main(Injector.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: net.spy.memcached.internal.CheckedOperationTimeoutException: Timed out waiting for operation - failing node: <unknown>
at net.spy.memcached.internal.OperationFuture.get(OperationFuture.java:167)
at net.spy.memcached.internal.OperationFuture.get(OperationFuture.java:140)
... 7 more
2014-07-04 17:27:27.995 INFO com.couchbase.client.CouchbaseConnection: Reconnecting due to failure to connect to {QA sa=10.250.110.205/10.250.110.205:11210, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0}
java.net.ConnectException: Connexion terminée par expiration du délai d'attente
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:735)
at net.spy.memcached.MemcachedConnection.handleIO(MemcachedConnection.java:677)
at net.spy.memcached.MemcachedConnection.handleIO(MemcachedConnection.java:436)
at com.couchbase.client.CouchbaseConnection.run(CouchbaseConnection.java:324)
java.lang.RuntimeException: Timed out waiting for operation
at com.couchbase.client.internal.HttpFuture.get(HttpFuture.java:75)
at com.couchbase.client.CouchbaseClient.getView(CouchbaseClient.java:430)
at com.t2s.injector.Injector.queryView(Injector.java:85)
at com.t2s.injector.Injector.main(Injector.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.util.concurrent.TimeoutException: Timed out waiting for operation
at com.couchbase.client.internal.HttpFuture.waitForAndCheckOperation(HttpFuture.java:93)
at com.couchbase.client.internal.HttpFuture.get(HttpFuture.java:82)
at com.couchbase.client.internal.HttpFuture.get(HttpFuture.java:72)
... 8 more
2014-07-04 17:27:53.249 WARN com.couchbase.client.CouchbaseConnection: Closing, and reopening {QA sa=10.250.110.205/10.250.110.205:11210, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0}, attempt 1.
2014-07-04 17:27:53.249 INFO com.couchbase.client.CouchbaseConnection: Reconnecting due to failure to connect to {QA sa=10.250.153.230/10.250.153.230:11210, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0}
java.net.ConnectException: Connexion terminée par expiration du délai d'attente
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:735)
at net.spy.memcached.MemcachedConnection.handleIO(MemcachedConnection.java:677)
at net.spy.memcached.MemcachedConnection.handleIO(MemcachedConnection.java:436)
at com.couchbase.client.CouchbaseConnection.run(CouchbaseConnection.java:324)
2014-07-04 17:28:08.534 INFO com.couchbase.client.ViewConnection: I/O reactor terminated
java code :
package com.t2s.injector;
import com.couchbase.client.CouchbaseClient;
import com.couchbase.client.protocol.views.Query;
import com.couchbase.client.protocol.views.View;
import com.couchbase.client.protocol.views.ViewResponse;
import com.couchbase.client.protocol.views.ViewRow;
import com.google.gson.Gson;
import com.t2s.injector.data.User;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public class Injector {
public static void main(String[] args) throws Exception {
System.out.println("Starting...");
try {
CouchbaseClient client = createClient("Users", "54.247.158.182");//, "54.74.200.186");
try {
insertData(client);
} catch (Exception e) {
e.printStackTrace();
}
try {
queryView(client, "users", "by_firstname");
} catch (Exception e) {
e.printStackTrace();
}
// Shutting down properly
client.shutdown(5, TimeUnit.SECONDS);
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static CouchbaseClient createClient(String bucket, String... ips) throws URISyntaxException, IOException {
// (Subset) of nodes in the cluster to establish a connection
Integer port = 8091;
List<URI> nodes = new ArrayList<>();
for (String ip : ips) {
nodes.add(new URI("http://" + ip + ":" + port + "/pools"));
}
// Password of the bucket (empty) string if none
String password = "";
// Connect to the Cluster
CouchbaseClient client = new CouchbaseClient(nodes, bucket, password);
System.out.println("Connected to " + client);
return client;
}
private static void insertData(CouchbaseClient client) throws InterruptedException, ExecutionException {
Gson gson = new Gson();
User user1 = new User("John", "Doe");
User user2 = new User("Matt", "Ingenthron");
User user3 = new User("Michael", "Nitschinger");
client.set("user101", gson.toJson(user1)).get();
client.set("user201", gson.toJson(user2)).get();
client.set("user301", gson.toJson(user3)).get();
}
private static void queryView(CouchbaseClient client, String designDoc, String viewName) {
/*
function (doc, meta) {
if(doc.firstname) {
emit(doc.firstname, doc.lastname);
}
}
*/
// 1: Load the View infos
View view = client.getView(designDoc, viewName);
// 2: Create a Query object to customize the Query
Query query = new Query();
query.setIncludeDocs(true); // Include the full document body
// 3: Actually Query the View and return the results
ViewResponse response = client.query(view, query);
// 4: Iterate over the Data and print out the full document
for (ViewRow row : response) {
System.out.println(row.getId() + ": " + row.getDocument());
}
}
}

I suspect that your clients cannot connect to the IP addresses which are returned by the cluster nodes. EC2 normally has a public and private address - can you check that your app server(s) can connect on ports 8091 & 11210 to each node?
See http://docs.couchbase.com/couchbase-manual-2.5/cb-admin/index.html#using-couchbase-in-the-cloud for details on how to configure - you'll generally have an easier time if you configure the Couchbase nodes to use hostnames and not IP addresses.

Dave is right, it appears you are connecting on the public IP, which will work for the initial connection, but the cluster is responding back with the private IP address space of the cluster and therefor you cannot connect to those perhaps.
Just to confirm, is your client local in AWS or remote?
Also, it is normally a bad practice to have your DB directly connected to the Internet. Open to the world just makes me nervous to even hear. You want to have your web/app servers on the public side and your db servers quite private with a web proxy to the Couchbase admin interface perhaps. Even better would be to put all of this in a VPC with Couchbase being in private subnets and your web/app and proxy in public subnets.
One other thing. It is best practice to have n+1 nodes in your connection string when connecting to a cluster in case one of the nodes is down when the app starts. I see that you have only one is all.

Related

Consumers from Rabbit were stopped and never recover

My spring boot application has been running with no erros during months using RabbitMq. In the last weeks, my consumer stopped working and I have to restart my application. Everyday I have to restart the application.
I noticed that it happens after this error in my log:
24-07-2021 07:20:08.138 [SimpleAsyncTaskExecutor-1] WARN o.h.e.jdbc.spi.SqlExceptionHelper - SQL Error: 17002, SQLState: 08006
24-07-2021 07:20:08.295 [SimpleAsyncTaskExecutor-1] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - IO Error: Socket read interrupted, Authentication lapse 682 ms.
24-07-2021 07:20:10.608 [SimpleAsyncTaskExecutor-1] WARN o.s.a.r.l.ConditionalRejectingErrorHandler - Execution of Rabbit message listener failed.
org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener method 'protected void br.jus.tjmg.certidaoEmissao.application.queues.EmissaoCriminalHistoricaConsumer.processaMensagem(br.jus.tjmg.certidao.webservice.ConsultaCertidoesRequest)' threw exception
at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:198)
at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:127)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:1477)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.actualInvokeListener(AbstractMessageListenerContainer.java:1400)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:1387)
at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:1366)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:848)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:832)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$700(SimpleMessageListenerContainer.java:78)
at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1073)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:450)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:378)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:474)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:289)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
at br.jus.tjmg.certidaoEmissao.application.services.EmissaoCertidaoService$$EnhancerBySpringCGLIB$$46f4e1c7.atualizarExecucaoCertidao(<generated>)
at br.jus.tjmg.certidaoEmissao.application.queues.EmissaoCriminalHistoricaConsumer.processaMensagem(EmissaoCriminalHistoricaConsumer.java:35)
at sun.reflect.GeneratedMethodAccessor49.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:181)
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:114)
at org.springframework.amqp.rabbit.listener.adapter.HandlerAdapter.invoke(HandlerAdapter.java:51)
at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:190)
... 10 common frames omitted
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to acquire JDBC Connection
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:115)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:109)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:136)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:254)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:262)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214)
at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:56)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.beginTransaction(HibernateJpaDialect.java:162)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:400)
... 25 common frames omitted
Caused by: java.sql.SQLRecoverableException: IO Error: Socket read interrupted, Authentication lapse 682 ms.
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:794)
at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:688)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:39)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:691)
at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection(OracleDataSource.java:384)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:273)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:198)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:176)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:106)
... 32 common frames omitted
Caused by: java.io.IOException: Socket read interrupted, Authentication lapse 682 ms.
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:790)
... 42 common frames omitted
Caused by: java.net.SocketTimeoutException: Socket read interrupted
at oracle.net.nt.TimeoutSocketChannel.read(TimeoutSocketChannel.java:152)
at oracle.net.ns.NIOHeader.readHeaderBuffer(NIOHeader.java:82)
at oracle.net.ns.NIOPacket.readFromSocketChannel(NIOPacket.java:139)
at oracle.net.ns.NIOPacket.readFromSocketChannel(NIOPacket.java:101)
at oracle.net.ns.NIONSDataChannel.readDataFromSocketChannel(NIONSDataChannel.java:80)
at oracle.jdbc.driver.T4CMAREngineNIO.prepareForReading(T4CMAREngineNIO.java:98)
at oracle.jdbc.driver.T4CMAREngineNIO.unmarshalUB1(T4CMAREngineNIO.java:534)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:485)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:252)
at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:499)
at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:1279)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:663)
... 42 common frames omitted
24-07-2021 07:20:20.230 [SimpleAsyncTaskExecutor-1] ERROR o.s.a.r.l.SimpleMessageListenerContainer - Stopping container from aborted consumer
24-07-2021 07:20:20.525 [SimpleAsyncTaskExecutor-1] INFO o.s.a.r.l.SimpleMessageListenerContainer - Waiting for workers to finish.
24-07-2021 07:20:20.584 [SimpleAsyncTaskExecutor-1] INFO o.s.a.r.l.SimpleMessageListenerContainer - Successfully waited for workers to finish.
I would like to avoid my consumer gets down. I have tried many different solutions, for example to restart my application after some events, but they didn't work.
public static void main(String[] args) {
context = SpringApplication.run(CertidaoApplication.class, args);
}
public static void restart() {
ApplicationArguments args = context.getBean(ApplicationArguments.class);
Thread thread = new Thread(() -> {
context.close();
context = SpringApplication.run(CertidaoApplication.class, args.getSourceArgs());
});
thread.setDaemon(false);
thread.start();
}
#EventListener
public void handleEvent(ListenerContainerConsumerTerminatedEvent e) {
logger.info("Restart spring boot. ListenerContainerConsumerTerminatedEvent");
CertidaoApplication.restart();
}
#EventListener
public void handleEvent(ListenerContainerConsumerFailedEvent e) {
logger.info("Restart spring boot. ListenerContainerConsumerFailedEvent");
CertidaoApplication.restart();
}
#EventListener
public void handleEvent(ContextStoppedEvent e) {
logger.info("Restart spring boot. ContextStoppedEvent");
CertidaoApplication.restart();
}
#EventListener
public void handleEvent(ContextClosedEvent e) {
logger.info("Restart spring boot. ContextClosedEvent");
CertidaoApplication.restart();
}
Here my configuration:
#Bean
public RabbitListenerContainerFactory<SimpleMessageListenerContainer> prefetchRabbitListenerContainerFactory(ConnectionFactory rabbitConnectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(rabbitConnectionFactory);
factory.setPrefetchCount(2);
factory.setDefaultRequeueRejected(Boolean.FALSE);
factory.setMessageConverter(jsonMessageConverter());
factory.setMissingQueuesFatal(Boolean.FALSE);
return factory;
}
My consumer:
#RabbitListener(queues = "${queue}", concurrency = "1", containerFactory = "prefetchRabbitListenerContainerFactory")
protected void processMessage(ConsultaRequest message) {
logger.info("Test" + message.getNumber());
Thanks a lot.

Connect to remote jms queue with Spring Boot

I'm trying to connect a remote JBOSS, JBOSS EAP 7, JMS queue with spring boot.
Below my code, I have only a configuration class and consumer class.
I see through logs that I'm connecting to localhost, but... WHY???
#Configuration
#EnableJms
public class ActiveMqConnectionFactoryConfig {
String queueName= "JMSTestQueueName";
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
public ConnectionFactory connectionFactory() {
try {
System.out.println("Retrieving JMS queue with JNDI name: " + CONNECTION_FACTORY);
JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiName(CONNECTION_FACTORY);
jndiObjectFactoryBean.setJndiEnvironment(getEnvProperties());
jndiObjectFactoryBean.afterPropertiesSet();
return (QueueConnectionFactory) jndiObjectFactoryBean.getObject();
} catch (NamingException e) {
System.out.println("Error while retrieving JMS queue with JNDI name: [" + CONNECTION_FACTORY + "]");
} catch (Exception ex) {
System.out.println("Error error");
ex.getStackTrace();
}
return null;
}
#Bean
Properties getEnvProperties() throws NamingException {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, "http-remoting://<REMOTE_ADDRESS>:8080?broker.persistent=false&broker.useJmx=false");
env.put(Context.SECURITY_PRINCIPAL, <USER>);
env.put(Context.SECURITY_CREDENTIALS, <PASSWORD>);
namingContext = new InitialContext(env);
return env;
}
#Bean
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) throws NamingException {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setConcurrency("3-10");
JndiDestinationResolver jndiDestinationResolver = new JndiDestinationResolver();
jndiDestinationResolver.setJndiEnvironment(getEnvProperties());
factory.setDestinationResolver(jndiDestinationResolver);
return factory;
}
}
Listener Class:
#Configuration
public class jmsListener {
#JmsListener(destination = "queue/JMSTestQueueName", containerFactory = "jmsListenerContainerFactory")
public void receive(Message message) {
System.out.println("Received Message: " + message);
}
}
The log:
2020-05-27 00:21:58.571 INFO 10368 --- [ main] o.apache.activemq.broker.BrokerService : Apache ActiveMQ 5.15.7 (localhost, ID:ITPC020248-60530-1590531718443-0:1) is starting
2020-05-27 00:21:58.576 INFO 10368 --- [ main] o.apache.activemq.broker.BrokerService : Apache ActiveMQ 5.15.7 (localhost, ID:ITPC020248-60530-1590531718443-0:1) started
2020-05-27 00:21:58.577 INFO 10368 --- [ main] o.apache.activemq.broker.BrokerService : For help or more information please see: http://activemq.apache.org
2020-05-27 00:21:58.617 INFO 10368 --- [ main] o.a.activemq.broker.TransportConnector : Connector vm://localhost started
2020-05-27 00:21:58.659 INFO 10368 --- [ main] jboss.ConsumerClass : Started ConsumerClass in 1.922 seconds (JVM running for 3.504)
Without ?broker.persistent=false&broker.useJmx=false on the JNDI URL I obtain this:
2020-05-27 19:38:34.680 INFO 19752 --- [dpoint" task-13] org.jboss.ejb.client.remoting : EJBCLIENT000016: Channel Channel ID 8f759d73 (outbound) of Remoting connection 336369ee to /172.16.68.80:8080 can no longer process messages
2020-05-27 19:38:37.479 INFO 19752 --- [ main] jboss.ConsumerClass : Started ConsumerClass in 7.194 seconds (JVM running for 9.26)
2020-05-27 19:38:42.772 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=0, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
2020-05-27 19:38:48.068 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=1, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
2020-05-27 19:38:53.401 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=2, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
2020-05-27 19:38:58.699 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=3, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
2020-05-27 19:39:04.006 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=4, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
2020-05-27 19:39:09.320 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=5, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
Your connectionFactory() needs to be a #Bean in order to inject it as an argument into your container factory factory method.
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) throws NamingException {
Since it's not a #Bean you are getting boot's default connection factory (presumably you have ActiveMQ on the class path).

Spring Websocket: How update and reflect the changes in runtime for the MessageBrokerRegistry object?

I am working with Spring Websocket and with ActiveMQ.
For the latter exits two servers, local and remote.
When the local server is enabled (remote is offline) the following works fine:
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableStompBrokerRelay("/topic", "/queue");
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}
When only the remote server is enabled (local is offline) the code shown above fails with the following:
[main] INFO o.s.m.s.s.StompBrokerRelayMessageHandler - Starting...
[main] INFO o.s.m.s.s.StompBrokerRelayMessageHandler - Connecting "system" session to 127.0.0.1:61613
...
[tcp-client-loop-nio-4] ERROR o.s.m.s.s.StompBrokerRelayMessageHandler - TCP connection failure in session _system_:
Failed to connect: Connection refused: /127.0.0.1:61613
io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: /127.0.0.1:61613
The solution is:
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableStompBrokerRelay("/topic","/queue").setRelayHost("192.168.1.88")
.setRelayPort(61613);
config.setApplicationDestinationPrefixes("/app");
config.setUserDestinationPrefix("/user");
}
My question is:
How in runtime is possible update the MessageBrokerRegistry object through the setRelayHost and setRelayPort methods and reflect these changes?. But It through the available #Configuration methods in the Spring Framework API.
Note: if one server is down and other remote server are available, I already have the new the values for the host and port.

application.properties not used when developing custom controller with MongoRepository in spring boot

I'm writing a simple spring boot backend application which uses MongoDB. I'm using spring data rest for the classic rest api calls and then developing a couple of custom controllers. I started develop it with a local mongo db instance and everything worked fine. Now I'm moving to a proper mongo db instance in another server and I've some problem using the custom controllers. I set spring.data.mongodb.host and spring.data.mongodb.port on my application.properties and the rest apis provided by spring data rest work successfully: I can insert and get data with no problem. But when I try to call the custom controller it looks like is still trying to connect to a local instance as I get this error message from the log:
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused (Connection refused)}}]
This is my repository
#RepositoryRestResource(collectionResourceRel = "deployment", path = "deployment")
public interface DeploymentRepository extends MongoRepository<DeploymentRecord, String> {
public List<DeploymentRecord> findByVmNameOrderByDeploymentTimeDesc(#Param("vmName") String vmName);
public DeploymentRecord findFirstByVmNameOrderByDeploymentTimeDesc(#Param("vmName") String vmName);
}
and this is the start of the custom controller:
#RestController
#EnableHypermediaSupport(type = {HypermediaType.HAL})
public class EnvironmentController {
#Autowired
private DeploymentRepository deploymentRepository;
#RequestMapping(value = "/listEnvironmentResources", method = RequestMethod.GET, produces = MediaTypes.HAL_JSON_VALUE)
public Resources<Resource<EnvironmentRecordResource>> getEnvironmentResourceList(){
This is the application (the default, basically)
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
The object data it's very simple, string fields and just getters.
How can I configure the custom controller to use the same configuration used by the self generated rest api that are on the application.properties?
Thanks,
Michele.
UPDATE
I tried to override the configuration creating my own
#Configuration
public class SpringMongoConfig extends AbstractMongoConfiguration{
#Autowired
private Environment env;
#Override
#Bean
public Mongo mongo() throws Exception
{
return new MongoClient(env.getProperty("spring.data.mongodb.host") , Integer.valueOf(env.getProperty("spring.data.mongodb.port")) );
}
public #Bean MongoTemplate mongoTemplate() throws Exception
{
return new MongoTemplate(mongo(), getDatabaseName());
}
#Override
protected String getDatabaseName() {
return "test";
}
}
Still, this is read only by the standard api, custom controller wants to connect to 127.0.0.1:
2017-11-23 11:44:02.441 INFO 7 --- [nio-8080-exec-3] org.mongodb.driver.cluster : Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2017-11-23 11:44:02.452 INFO 7 --- [127.0.0.1:27017] org.mongodb.driver.cluster : Exception in monitor thread while connecting to server 127.0.0.1:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:63) ~[mongodb-driver-core-3.4.3.jar!/:na]
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) ~[mongodb-driver-core-3.4.3.jar!/:na]
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113) ~[mongodb-driver-core-3.4.3.jar!/:na]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_151]
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_151]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_151]
at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_151]
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:57) ~[mongodb-driver-core-3.4.3.jar!/:na]
at com.mongodb.connection.SocketStream.open(SocketStream.java:58) ~[mongodb-driver-core-3.4.3.jar!/:na]
... 3 common frames omitted

Kite Dataset map-reduce

I am trying to do map-reduce with kite-dataset api.
I have followed below urls to refer.
https://community.cloudera.com/t5/Kite-SDK-includes-Morphlines/Map-Reduce-with-Kite/td-p/22165
https://github.com/kite-sdk/kite/blob/master/kite-data/kite-data-mapreduce/src/test/java/org/kitesdk/data/mapreduce/TestMapReduce.java
My code snippet as below
public class MapReduce {
private static final String sourceDatasetURI = "dataset:hive:test_avro";
private static final String destinationDatasetURI = "dataset:hive:test_parquet";
private static class LineCountMapper
extends Mapper<GenericData.Record, Void, Text, IntWritable> {
#Override
protected void map(GenericData.Record record, Void value,
Context context)
throws IOException, InterruptedException {
System.out.println("Record is "+record);
context.write(new Text(record.get("index").toString()), new IntWritable(1));
}
}
private Job createJob() throws Exception {
System.out.println("Inside Create Job");
Job job = new Job();
job.setJarByClass(getClass());
Dataset<GenericData.Record> inputDataset = Datasets.load(sourceDatasetURI, GenericData.Record.class);
Dataset<GenericData.Record> outputDataset = Datasets.load(destinationDatasetURI, GenericData.Record.class);
DatasetKeyInputFormat.configure(job).readFrom(inputDataset).withType(GenericData.Record.class);
job.setMapperClass(LineCountMapper.class);
DatasetKeyOutputFormat.configure(job).writeTo(outputDataset).withType(GenericData.Record.class);
job.waitForCompletion(true);
return job;
}
public static void main(String[] args) throws Exception {
MapReduce httAvroToParquet = new MapReduce();
httAvroToParquet.createJob();
}
}
I am using HDP 2.3.2 box ,creating assembly jar and submitting my application through spark-submit.
I am getting below error when I submit my application.
2015-12-18 04:09:07,156 WARN [main] org.apache.hadoop.hdfs.shortcircuit.DomainSocketFactory: The short-circuit local reads feature cannot be used because libhadoop cannot be loaded.
2015-12-18 04:09:07,282 INFO [main] org.apache.hadoop.mapreduce.v2.app.MRAppMaster: OutputCommitter set in config null
2015-12-18 04:09:07,333 WARN [main] org.kitesdk.data.spi.Registration: Not loading URI patterns in org.kitesdk.data.spi.hive.Loader
2015-12-18 04:09:07,334 INFO [main] org.apache.hadoop.service.AbstractService: Service org.apache.hadoop.mapreduce.v2.app.MRAppMaster failed in state INITED; cause: org.apache.hadoop.yarn.exceptions.YarnRuntimeException: org.kitesdk.data.DatasetNotFoundException: Unknown dataset URI: hive://{}:9083/default/test_parquet. Check that JARs for hive datasets are on the classpath.
org.apache.hadoop.yarn.exceptions.YarnRuntimeException: org.kitesdk.data.DatasetNotFoundException: Unknown dataset URI: hive://{}:9083/default/test_parquet. Check that JARs for hive datasets are on the classpath.
at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$1.call(MRAppMaster.java:478)
at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$1.call(MRAppMaster.java:458)
at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.callWithJobClassLoader(MRAppMaster.java:1560)
at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.createOutputCommitter(MRAppMaster.java:458)
at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.serviceInit(MRAppMaster.java:377)
at org.apache.hadoop.service.AbstractService.init(AbstractService.java:163)
at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$4.run(MRAppMaster.java:1518)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1657)
at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.initAndStartAppMaster(MRAppMaster.java:1515)
at org.apache.hadoop.mapreduce.v2.app.MRAppMaster.main(MRAppMaster.java:1448)
Caused by: org.kitesdk.data.DatasetNotFoundException: Unknown dataset URI: hive://{}:9083/default/test_parquet. Check that JARs for hive datasets are on the classpath.
at org.kitesdk.data.spi.Registration.lookupDatasetUri(Registration.java:109)
at org.kitesdk.data.Datasets.load(Datasets.java:103)
at org.kitesdk.data.Datasets.load(Datasets.java:165)
at org.kitesdk.data.mapreduce.DatasetKeyOutputFormat.load(DatasetKeyOutputFormat.java:510)
at org.kitesdk.data.mapreduce.DatasetKeyOutputFormat.getOutputCommitter(DatasetKeyOutputFormat.java:473)
at org.apache.hadoop.mapreduce.v2.app.MRAppMaster$1.call(MRAppMaster.java:476)
... 11 more
I am not getting what's wrong ? Is there any class-path problem ? If yes then where do I set it ?
You effectively have a classpath problem
Your project is missing org.kitesdk:kite-data-hive
You can
Add this jar to your fat jar before submitting it to Spark
Tells Spark to add it to your classpath when you submit

Resources