Connection refused: RabbitMQ - java

I am new to RabbitMQ and trying out simple example on it.
Below is my java source:
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}
And am getting below error:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at com.rabbitmq.client.impl.FrameHandlerFactory.create(FrameHandlerFactory.java:32)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:588)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:612)
at .Send.main(Send.java:15)
Any suggestions please?

Do you have your RabbitMQ server installed?
Also do you have the rabbitmq-client.jar and its dependencies on the classpath?
Try running this from your terminal:
java -cp .:commons-io-1.2.jar:commons-cli-1.1.jar:rabbitmq-client.jar Send

Related

How to read messages from a rabbitmq queue running in a local docker container

I am running rabbitmq in my local mac in docker container. I accessed it through the GUI (at port 15672) in browser and created a queue, exchange and published some messages in the queue. I am trying to write a java application which can read the messages from the queue and print it in the console but I am running in to this error.
rjashnani-ltm:rabbitmq rjashnani$ java -cp .:amqp-client-5.7.1.jar:slf4j-api-1.7.26.jar:slf4j-simple-1.7.26.jar Recv
Exception in thread "main" java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
I created docker container using this command
docker run -d --hostname my-rabbit --name some-rabbit2 -p 15672:15672 -p 5672:5672 rabbitmq:3-management
Here is my Java application code
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
public class Recv {
private final static String QUEUE_NAME = "test-queue";
public static void main(String[] argv) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setPort(5762);
factory.setUsername("guest");
factory.setPassword("guest");
factory.setVirtualHost("/");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Received '" + message + "'");
};
channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });
}
}
docker run -it --rm --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management
Running docker with -it argument, resolved the issue.

Connection refused [Tarantool + java client]

When i'm trying to connect to tarantool server i get the following error:
Exception in thread "main" java.net.ConnectException: Connection
refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native
Method) at
java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at
java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at
java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at
java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at
java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at
java.net.Socket.connect(Socket.java:589) at
java.net.Socket.connect(Socket.java:538) at
java.net.Socket.(Socket.java:434) at
java.net.Socket.(Socket.java:211) at
TarantoolKt.main(Tarantool.kt:37)
My code:
class Tarantool {
val client: TarantoolClient
init {
val config: TarantoolClientConfig = TarantoolClientConfig()
config.apply {
username = "test"
password = "test"
}
val socketChannelProvider: SocketChannelProvider = SocketChannelProvider { _, p1 ->
when(p1) {
null -> {
println("Trying to connect . . .")
SocketChannel.open(InetSocketAddress("192.168.1.254", 3301)) // <- error
}
else -> {
p1.printStackTrace(System.out)
null!!
}
}
}
client = TarantoolClientImpl(socketChannelProvider, config)
}
}
fun main(args: Array<String>): Unit {
val client: Tarantool = Tarantool()
println(client.client.isAlive)
}
I get the same error when i'm trying to use different ip
It's the same as in tutorial here: https://github.com/tarantool/tarantool-java/
I'd also created the test user using this commands:
box.schema.user.create('test', { password = 'test' })
box.schema.user.grant('test', 'execute,read,write', 'universe')
I use docker for tarantool and i tried to ping IPs from windows 7 cmd and it works.
Thank you!
SOLVED

How to connect wordpress database with JAVA ? (mysql)

I dont know much about the connection proccess i'm trying to connect wordpress database without creating new database with my remotedesktop IP in mysql. Normally i can connect localhost and i can connect to database that created with remote ip. In my server mydatabase host name/Ip adress is localhost, as i said i dont know the whole connection between url request,wp-config file and mysql. I think i'm sending request with url to wp-config and it is connecting to my localhost. Anyway i want to connect to my remotedesktop's localhost with JAVA but i couldn't. Let me explain with code . Hope i could explain myself.
Thanks in advance.
Here are the codes :
wp-config.php
define('DB_NAME', 'mydbname');
define('DB_USER', 'mydbuser');
define('DB_PASSWORD', 'mydbpass');
define('DB_HOST', '127.0.0.1');
My connection code :
public class Dt_page {
public static DataSource getDataSource(int server) {
String database_driver = null;
String database_adres = null;
String dbuser = null;
String dbpass = null;
ConnectionFactory connectionFactory;
switch (server) {
case 1://profile server
database_driver = "com.mysql.jdbc.Driver";
database_adres = "jdbc:mysql://MY_REMOTE_DESKTOP_IP:3306/?useUnicode=true&characterEncoding=UTF-8&rewriteBatchedStatements=true";
dbuser = "mydbuser";
dbpass = "mydbpass";
}
try {
Class.forName(database_driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Dt_page.class.getName()).log(Level.SEVERE, null, ex);
}
Properties props = new Properties();
props.put("user", dbuser);
props.put("password", dbpass);
props.put("autoReconnect", "true");
props.put("autoReconnectForPools", "true");
props.put("validationQuery", "SELECT 1 from dual;");
props.put("testWhileIdle","true");
connectionFactory = new DriverManagerConnectionFactory(database_adres, props);
GenericObjectPool connectionPool = new GenericObjectPool(null, 12, GenericObjectPool.WHEN_EXHAUSTED_GROW, 60*30, 12,true,true);
GenericKeyedObjectPoolFactory keyedObjectPoolFactory = new GenericKeyedObjectPoolFactory(null);
PoolableConnectionFactory poolableConnectionFactory =
new PoolableConnectionFactory(connectionFactory,
connectionPool,
keyedObjectPoolFactory,
"select 1",
30,
null,
false,
true);
PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
return dataSource;
And SQL
QueryRunner qr;
qr = new QueryRunner(Dt_page.getDataSource(1));
try {
List<Object[]> v = qr.query("Select meta_value from mydbname.wp_favorite", new ArrayListHandler());
System.out.println(v.size());
for (Object[] objects : v) {
for (Object object : objects) {
System.out.println(object);
}
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
}
Error Log:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1014)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:2367)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2288)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:822)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:317)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:187)
at org.apache.commons.dbcp.DriverManagerConnectionFactory.createConnection(DriverManagerConnectionFactory.java:78)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:1188)
at org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:106)
at org.apache.commons.dbutils.AbstractQueryRunner.prepareConnection(AbstractQueryRunner.java:175)
at org.apache.commons.dbutils.QueryRunner.query(QueryRunner.java:304)
at tazedizi.TazeDizi.main(TazeDizi.java:29)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1117)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:355)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2461)
at com.mysql.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:2306)
... 19 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:241)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:259)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:305)
... 21 more
Two things to check:
Are you sure that your mysql server is configurated to listend on MY_REMOTE_DESKTOP_IP ?
Are you sure that your firewall (iptable...) allows connexion on MY_REMOTE_DESKTOP_IP on tpc port 3306 ?

Python Server / Java Client "Connection refused: connect"

I am communicating using TCP Socket.
While Working, a problem arises
Client can't make 'Socket' Instance.
Strange Point is that (In Server using Python)
Using 'socket' class in python don't cause problem,
but using 'SocketServer.TCPServer' class in python cause problem
This is my environment.
Server : Python
Client : Java / Many Users will try connect.
Server Code (using Python):
SooMain.py
if name == "main":
server = SooServer('localhost', PORT_DEBUG, SooRequestHandler)
server.serve_forever()
SooServer.py
class SooServer(SocketServer.TCPServer):
"This is Server For Project201201"
def __init__(self,
host='localhost',
port=PORT_DEBUG,
handler=SooRequestHandler):
#SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
SocketServer.TCPServer.__init__(self, (host, port), handler)
print "SooServer <State> __init__"
self.abort=0
self.timeout=10
def shutdown(self):
SocketServer.ThreadingTCPServer.shutdown(self)
print "SooServer <State> shutdown"
Client Code (using Java):
TestJava.java
public class TestJava {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
try {
String[] aStrData = {
"Test",
"Test" };
InetAddress m_oInetAddr = InetAddress.getByName(DEBUG_ADDR);
Socket m_oSocket = new Socket(m_oInetAddr, DEBUG_PORT); //This Line Makes Exception!!!!!
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(m_oSocket.getOutputStream())), true);
int nNumData = aStrData.length;
out.println(Integer.toString(nNumData));
for (int i=0 ; i<nNumData ; i++) {
out.println(aStrData[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error Code (using Java):
Releated Line : Socket m_oSocket = new Socket(m_oInetAddr, DEBUG_PORT);
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:241)
at TestJava.main(TestJava.java:51)

Error in making a socket connection

I am trying to run the program below, but I am getting this error:
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at com.rabbitmq.client.ConnectionFactory.createFrameHandler(ConnectionFactory.java:445)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:504)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:533)
at Recieve.main(Recieve.java:14)
The program I am trying to run is:
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv) throws java.io.IOException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}
I am not aware of making a socket connection, please let me know how to resolve this.
Here are the steps you should follow for your code to work:
Download and install the latest Erlang.
Download the RabbitMQ server.
Install RabbitMQ Server
Compile and run your code and it should work by now.
Hope this helps.

Categories

Resources