Whenever I try to connect to my Redis server from my Java application using Jedis, I get JedisConnectionException: Failed to connect to any host resolved for DNS name. The Java application runs on the same machine as the Redis server.
When I check the Redis server's status using systemctl, it's online and running without problems. I also connected to the Redis client via terminal using command-line on the Linux machine it is running on, authenticated and performed PING in which PONG was returned to make sure the Redis was up running.
Redis configuration
I have bind and requirepass un-commented in the redis.conf and looks like following (not my entire config, of course):
bind 127.0.0.1
requirepass mypassword
port 6379
This is the code I am using:
private void setupRedis(RedisCredentials credentials) {
final GenericObjectPoolConfig<Jedis> poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(0);
Jedis jedis;
try (JedisPool pool = new JedisPool(poolConfig, credentials.getIp(), credentials.getPort())) {
jedis = pool.getResource();
}
jedis.auth(credentials.getPassword());
jedis.connect();
log.info("Redis connection was established.")
}
I am a bit new to working with Redis therefor I wasn't sure on how much information to include in my post. All and any help is very much appreciated!
Tried
I tried the following code provided above multiple times. I have also tried restarting the Redis server and running the code again, with no successful try.
Expected to happen
For the application to log "Redis connection was establish" and to receive no errors in the process.
Resulted
The console logs the redis.clients.jedis.exceptions.JedisConnectionException: Failed to connect to any host resolved for DNS name and the application therefore obviously does not managed to establish a connection to Redis.
So I have an Azure App Service and I want it to be able to connect to mongo db atlas. For our Atlas setup there is a peering connection between our managed environment on azure (and the vnet it all sits in) and our mongo db cluster.
The mongo cluster is setup with "Connect via peering only" which we can't change. This means we can't connect to our db with any old public ip address -It has to come from the vnet it's peered with. The vms (from within the peered vnet) are able to access the db no problem.
I tried with the app service to connect to the db with the same connection string that worked for the vm. It returned a the error:
java.net.ConnectException: Connection refused (Connection refused)}}, {address=MYMONGOADDRESS.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused (Connection refused)}}]
This is expected due to the reasons above. However I setup the vnet integration for the app service
. I created a dedicated subnet as described for the app service and whitelisted the ip range in mongo. However I still couldn't connect to the db after using this vnet integration. I also got a very similar error but slightly different.
{java.net.SocketTimeoutException: connect timed out}}, {address=MYMONGOADDRESS.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}]
Where instead of a connection refused I'm not getting a connection time out. I've repeated this a few times and get the same result.
Anyone know why these errors are different and any help in being able to connect to the db from my azure app service?
Is there any firewall or network security group? What the network peering status is? If it shows « initiated » then this means it has not been completed. Network peering has to be done on each ends. If it shows « connected », then I would look for firewall or network security groups.
See this
https://docs.atlas.mongodb.com/security-vpc-peering/#vpc-peering
No idea if this can apply to your case but this question was the first and only that came up when I was searching for something similar.
In my case I have a MongoDB Atlas deployed on Azure and an app running in AKS. I set up peering as documented but still could not connect from the app container in AKS to the MongoDB. Turns out the problem was an incorrect connection string.
Atlas has a different URL when connecting directly and when connecting through a peer network:
# Direct connection
mongo "mongodb+srv://<cluster>.<something>.mongodb.net/<dbname>"
# Peered connection (note the -pri)
mongo "mongodb+srv://<cluster>-pri.<something>.mongodb.net/<dbname>"
As an additional note, I configured the Atlas Network Acces IP address list with the CIDR of the Azure VN Subnet used in AKS. (Under Virtual Network > Subnets > IPv4)
Trying to connect Atlas cluster via Java driver using MongoDB version 3.6.
So, I'm writting like:
MongoClientURI uri = new MongoClientURI("mongodb+srv://admin:mypassword#cluster0-ox90k.mongodb.net/test?retryWrites=true");
MongoClient mongoClient = new MongoClient(uri);
In this case the error is:
java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with 'mongodb://'
at com.mongodb.ConnectionString.<init>(ConnectionString.java:203)
at com.mongodb.MongoClientURI.<init>(MongoClientURI.java:176)
at com.mongodb.MongoClientURI.<init>(MongoClientURI.java:158)
at project.Bot.check(Bot.java:30)
at project.Bot.onUpdateReceived(Bot.java:104)
at java.util.ArrayList.forEach(ArrayList.java:1249)
at org.telegram.telegrambots.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:309)
When the program starts with snippet using MongoDB version 3.6 or later without +srv:
MongoClientURI uri = new MongoClientURI("mongodb://admin1:mypassword#cluster0-ox90k.mongodb.net/test?retryWrites=true");
MongoClient mongoClient = new MongoClient(uri);
I'm getting an error:
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=cluster0.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: cluster0.mongodb.net}, caused by {java.net.UnknownHostException: cluster0.mongodb.net}}]
at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:369)
at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75)
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71)
at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63)
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:201)
at com.mongodb.operation.CountOperation.execute(CountOperation.java:206)
at com.mongodb.operation.CountOperation.execute(CountOperation.java:53)
at com.mongodb.Mongo.execute(Mongo.java:772)
at com.mongodb.Mongo$2.execute(Mongo.java:759)
at com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:185)
at com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:170)
at project.Bot.check(Bot.java:36)
at project.Bot.onUpdateReceived(Bot.java:103)
at java.util.ArrayList.forEach(ArrayList.java:1249)
at org.telegram.telegrambots.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:309)
In POM file I have dependency:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.6.0</version>
</dependency>
Also, when I'm starting mongo my database is added to this address mongodb://127.0.0.1:27017, but I added path to the cluster not for this. Maybe I need to write path to concrete cluster or?
Ofc, I have admin-user. In addition, I can connect via Compass to my cluster and from shell. mongod process is started. This error appears only, when I'm running in IDE. Same issue probably here.
Does anyone know how to solve this error? I appreciate any help.
Solved it!
So, what I've done:
I tried only to connect to tier cluster via driver3.6 and wrote
mongodb+srv://user:#cluster0-ox90k.mongodb.net/test?retryWrites=true
I always get an error: Connection strings must start with 'mongodb://'.
Okay, I deleted the snippet +srv and wrote the same way
mongodb://user:#cluster0-ox90k.mongodb.net/test?retryWrites=true
and get again the error:
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=cluster0-ox90k.mongodb.net:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException: cluster0-ox90k.mongodb.net}, caused by {java.net.UnknownHostException: cluster0-ox90k.mongodb.net}}]
So, I wrote via driver3.4 or earlier like
mongodb://user:<PASSWORD>#cluster0-shard-00-00-ox90k.mongodb.net:27017,cluster0-shard-00-01-ox90k.mongodb.net:27017,cluster0-shard-00-02-ox90k.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true
and finally it solved.
Note: You can get this connection string from the Atlas management console by setting your Java driver to '3.4 or later'. This will help you avoid having to come up with the connection string yourself.
Updated: if you want to use drivers 3.7+, you need to write instead of format connection (and to avoid my issues above)
MongoClientURI uri = new MongoClientURI("mongodb+srv://admin:mypassword#cluster0-ox90k.mongodb.net/test?retryWrites=true");
MongoClient mongoClient = new MongoClient(uri);
another variant using MongoClients.create() (as of the 3.7 release), and as mentioned here:
MongoClient mongoClient = MongoClients.create("mongodb+srv://admin:mypassword#cluster0-ox90k.mongodb.net/test?retryWrites=true");
Note: the password need to write not like mongodb://user:<mypassword>#...,
just in format mongodb://user:mypassword#...
without braces <>.
There seem to be a few issues here
First
3.6.0 is not the Mongo driver library that was actually loaded into your application classpath; I suspect that you were previously testing with an old version, and recently updated the POM? You were previously using version 3.2.0.
How do I know this?
I started digging through the code, and at version 3.6.0, the error message you provided is nowhere near line 203. And also, you can see that the above linked code has support for the +srv.
Browing back through previousl releases, I finally found that error massge on line 203, back at release 3.2.0.
Long story short, trying doing a Maven clean, and rebuild.
Relaunch Eclipse to pick up new dependencies if a project refresh does not help.
Second
MongoTimeoutException: Timed out after 30000 ms while waiting for a server
This one is highly likely a firewall / access control group configuration issue, in that the firewall is blocking the packets from reaching your Atlas cluster.
See adding addresses to the whitelist.
One more important note:
in this string:
MongoClientURI uri = new MongoClientURI("mongodb+srv://admin:mypassword#cluster0-ox90k.mongodb.net/test?retryWrites=true");
test ==> is a Db name, before making this connection, DB should exist.
The above-mentioned solution is not working in the current assignment, because I'm working on the Spring-boot framework assignment.
I have got error as Caused by: java.net.UnknownHostException: khweshacluster0.brzta.mongodb.net
To Solve this I have to take configurations from below
Take Highlighted URL
& make below format URL as
spring.data.mongodb.uri=mongodb://:#<Atlas_cluster_URL>
& same update in application.properties
as follows,
spring.data.mongodb.uri=mongodb://username:password#khweshacluster0-shard-00-00.brzta.mongodb.net:27017,khweshacluster0-shard-00-01.brzta.mongodb.net:27017,khweshacluster0-shard-00-02.brzta.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-3b1nqz-shard-0&authSource=admin&retryWrites=true&w=majority
I faced same issue when trying to connect from my tomcat application to MongoDB.
I had tomcat 9.0 and MongoDB 4.2 installed with application using Mongo Driver 3.12.3
Error: org.springframework.dao.DataAccessResourceFailureException: Timed out after
30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN,
servers=[{address=#127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception=
{com.mongodb.MongoSocketException: #127.0.0.1}, caused by
{java.net.UnknownHostException: #127.0.0.1}}]; nested exception is
com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect.
Client view of cluster state is {type=UNKNOWN, servers=[{address=#127.0.0.1:27017,
type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketException:
#127.0.0.1}, caused by {java.net.UnknownHostException: #127.0.0.1}}]
I tried creating sample Java application to connect DB and it worked, however it was not able to connect from web application.
So created user for DB and assigned role userAdmin, which worked for me.
Not working Conn String - mongodb://#127.0.0.1:27017/docs <br>
Working Conn string - mongodb://docs_local:docs#127.0.0.1:27017/docs
i had this issue and i checked the documentation
i created a configuration class like this
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AppConfig {
public #Bean
MongoClient mongoClient() {
return MongoClients.create("mongodb://localhost:27017");
}
}
you can put your uri where "mongodb://localhost:27017" is
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#reference
I had the similar issue and solved it by selecting Node driver version 2.2.12 or later and it will give me a connection string starting with 'mongodb://'
I am getting this issue when I deploy redis server and spring server in two different servers and try to connect to spring server through my application.
App Details:
We have mobile application which publish gps coordinates to spring server using stomp. In the spring server we create jedis pubsub connection and publish those gps data to our web application and web users subscribe to those jedis pubsub connections.
Library versions:
stomp:1.7.1
jedis: 2.8.1
spring: 4.3.0
Working scenarios:
*Deploy spring server in my local machine and redis server in remote production server.
*Deploy spring server in remote server and redis server in same remote server where spring server is deployed.
Partially Working scenarios:
*Deploy spring server in remote server and redis server in different remote server where spring server is deployed. In this scenario I monitor redis server using redis cli and I can see the "HGETALL", "PUBLISH" key words with its data. But the same time I got following error in spring server:
Caused by:
java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
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.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at redis.clients.jedis.Connection.connect(Connection.java:158)
... 4 more
redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused (Connection refused)
at redis.clients.jedis.Connection.connect(Connection.java:164)
at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:80)
at redis.clients.jedis.Connection.setTimeoutInfinite(Connection.java:68)
at redis.clients.jedis.Jedis.subscribe(Jedis.java:2626)
at shipxpress.pubsubservice.controllers.SubscriberThread.run(MainController.java:227)
The spring server can successfully depoyed to the server and exception occurs when jedis try to publish or subscripe to the connection.
I can succesfully ping to redis server from the server where we deploy the spring server through the redis-cli and the redis server prtected-mode is no and and bind ip is set to 0.0.0.0
Links:
I went through following links but no luck
Redis bind to more than one IP
https://github.com/xetorthio/jedis/issues/1405
Cannot connect to redis using jedis
This issue means that the Spring remote server is not able to communicate with the other remote server(Redis server) on the default Redis port.
Maybe you could confirm this by trying to access the Remote Redis server from the other remote Server using netstat from the console.
I had the same issue, and the simplest solution was
Find the following line in your redis.conf file and comment it out:
bind 127.0.0.1
By adding a # in front of it:
# bind 127.0.0.1
and change the line protected-mode yes to be protected-mode no
save your redis.conf and restart redis using the config file
redis-server /configFileLocation
I am trying to test Amazon's new Memcached client with AutoDiscovery. I have one memcached node which I am able to connect to using XMemcached 1.3.5 as well as a standard SpyMemcached library.
I am following the instructions here: http://docs.amazonwebservices.com/AmazonElastiCache/latest/UserGuide/AutoDiscovery.html
The code is almost identical to the example and is:
String configEndpoint = "<server name>.rgcl8z.cfg.use1.cache.amazonaws.com";
Integer clusterPort = 11211;
MemcachedClient client = new MemcachedClient(new InetSocketAddress(configEndpoint, clusterPort));
client.set("theKey", 3600, "This is the data value");
I see the following in the logs when I create the connection. The error happens when I try to set a value:
2013-01-04 22:05:30.445 INFO net.spy.memcached.MemcachedConnection: Added {QA sa=/<ip>:11211, #Rops=0, #Wops=0, #iq=0, topRop=null, topWop=null, toWrite=0, interested=0} to connect queue
2013-01-04 22:05:32.861 INFO net.spy.memcached.ConfigurationPoller: Starting configuration poller.
2013-01-04 22:05:32.861 INFO net.spy.memcached.ConfigurationPoller: Endpoint to use for configuration access in this poll NodeEndPoint - HostName:<our-server>.rgcl8z.cfg.use1.cache.amazonaws.com IpAddress:<ip> Port:11211
2013-01-04 22:05:32.950 WARN net.spy.memcached.MemcachedClient: Configuration endpoint timed out for config call. Leaving the initialization work to configuration poller.
Exception in thread "main" java.lang.IllegalStateException: Client is not initialized
at net.spy.memcached.MemcachedClient.checkState(MemcachedClient.java:1623)
at net.spy.memcached.MemcachedClient.enqueueOperation(MemcachedClient.java:1617)
at net.spy.memcached.MemcachedClient.asyncStore(MemcachedClient.java:474)
at net.spy.memcached.MemcachedClient.set(MemcachedClient.java:905)
at com.thinknear.venice.initializers.VeniceAssets.main(VeniceAssets.java:227)
I've tried this both locally and on a EC2 instance (I can connect using other libraries to the nodes)
I've tried using both 1.4.5 and 1.4.14 Memcached engines
I relaxed the security group constraints as well just in case
Any thoughts on why the config endpoint would be timing out?
Client is not initialised:
You can not directly connect to amazon elastic cache node through your local machine you can only access it through your ec2 machiene.If you want to check you can telnet from your local machine it will not connect I also suufered from the same problem .You can telnet it from your Ec2 machine.so try your code at ec2 machine it will work.
Do telnet on memcache server to check connectivity ,in mine case it was not listed so was not able to made connection ,
problem solved by listing my server to memcache.