Unable to save java object in Redis - java

I was trying to run the following example in my machine:
https://examples.javacodegeeks.com/enterprise-java/spring/spring-data-redis-example/
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new ClassPathResource("/spring/spring-config.xml").getPath());
RedisRepo redisRepo = (RedisRepo)context.getBean(“redisRepo");
try{
JedisPool pool = new JedisPool(new JedisPoolConfig(), "x.x.x.x”);
Jedis jedis = pool.getResource();
System.out.println("Connected to Redis”);//connected to Redis
System.out.println("server is running: "+jedis.ping());//PONG
System.out.println("current keys are :"+jedis.keys(“*”));//[ ]
Employee s = new Employee();
s.setId(1);
s.setName(“abc”);
redisRepo.saveState(s);
System.out.println("server is running: "+jedis.ping());//PONG
System.out.println("Finding the One : "+redisRepo.getState(1);//Finding the one :null
}
catch(Exception e){
logger.error(e.getMessage(), e);
}
}
But getting the following error while trying to save the model object:
Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
I would like to add that I can test the connection to redis server by pinging.How can I resolve this issue to persist data in Redis?

I could resolve the issue to save data on local instance by running redis locally.While to save data on remote server I had import resource in the main class.Like:
#ImportResource({classpath:path-to-youXML})

Related

JedisPool Connection Refused Spring Boot

I have a small spring boot application that I am trying to integrate with Redis using Jedis client.
I set up the Jedis pool to point towards a Redis docker container running locally.
#Bean
public JedisPool jedisPool() {
JedisPool jedisPool = null;
try {
URI redisUri = new URI("redis://localhost:6379");
jedisPool = new JedisPool(poolConfig(), redisUri, 20000, null, null, null);
} catch (URISyntaxException e) {
logger.error("Failed to create the redis pool: ", e);
}
return jedisPool;
}
I have a RedisService that makes use of the JedisPool and perform transactions against the Redis Server.
#Autowired
JedisPool jedisPool;
#Override
public String retrieve(String key) {
Jedis jedis = jedisPool.getResource();
String json = jedis.get(key);
jedis.close();
return json;
}
#Override
public void store(String key, String value) {
Jedis jedis = jedisPool.getResource();
jedis.set(key, value);
jedis.expire(key, keyExpire);
jedis.close();
}
When running the app I get this exception
redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused (Connection refused)
I am able to connect to the Redis Server via redis-cli but not from my spring boot app.
Any ideas on how to solve this issue?
Try to use http://localhost:6379 instead your current URI

Getting error connecting for the first time to HBase using Phoenix driver

Using Phoenix driver I am connecting to HBase. Everything works, but there is an error stacktrace in the log while getting a connection. Again, it works fine, functionally no issues.
DataSource dataSource = getDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("test", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMappers("co.mybatis.mapper");
return new SqlSessionFactoryBuilder().build(configuration);
public static DataSource getDataSource() {
return new UnpooledDataSource("org.apache.phoenix.jdbc.PhoenixDriver", CDH_UAT, "", "") {
#Override
public Connection getConnection() throws SQLException {
Connection connection = super.getConnection();// i see error stacktrace here
connection.setSchema("xxx");
return connection;
}
}}
java.util.concurrent.ExecutionException: org.apache.hadoop.hbase.security.AccessDeniedException: org.apache.hadoop.hbase.security.AccessDeniedException: Insufficient permissions (user=userid#mydomain.COM, scope=SYSTEM, params=[namespace=SYSTEM,table=SYSTEM:CATALOG],action=CREATE)
For the first time, it prints error stacktrace, but afterwards all looks good. It seems for the first time while getting the connection it tries to upsert into system catalog table, not sure why.
How do I get rid of this error?

Java RMI connection over internet

I'm trying to get remote objects from a server hosted on different network. I'm able to connect on same machine and on same network, but when I try to get it from different network I get:
Connection refused to host: 192.168.1.131; nested exception is: java.net.ConnectException: Connection timed out: connect
It seems that lookup function is searching at wrong network. I tried to use System.setProperty but it doesn't work. Here the code:
Server
public class Main {
public static void main(String[] args) {
try{
System.out.println("Init server...\n");
TestInterface test = new TestImplement();
System.setProperty("java.rmi.server.hostname", "95.247.x.x");
System.out.println("Reg RMI...\n");
Registry rmiRegistry = LocateRegistry.createRegistry(5555);
rmiRegistry.rebind("Test" , test);
System.out.println("Reg completed!\n");
}catch(Exception e){
e.printStackTrace();
}
}
}
Client
...
registryRMI = LocateRegistry.getRegistry("95.247.x.x",5555);
TestInterface testClient = (TestInterface)registryRMI.lookup("Test");
...
Do I need to set java.rmi.server.hostname in client jar as well?
TestInterface test = new TestImplement();
System.setProperty("java.rmi.server.hostname", "95.247.x.x");
You need to set java.rmi.server.hostname before exporting any remote objects. Doing it afterwards is too late.
System.setProperty("java.rmi.server.hostname", "95.247.x.x");
TestInterface test = new TestImplement();

java jedis (redis) cannot connect

I'm trying to connect to Redis using Jedis in my java application. I'm instantiating a JedisPool object, and when I get the resource, it throws an exception saying it cannot return the resource. What is weird though is if I just instantiate a Jedis object, it connects without problems, and I can change data.
Here's my RedisDatabase class:
package me.joeleoli.proxylink.database;
import me.joeleoli.proxylink.ProxyLink;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisDatabase {
private JedisPool pool;
public RedisDatabase(String host, int port, String password) {
ProxyLink.getInstance().getLogger().info("Attempting to establish Redis connection " + host + ":" + port);
this.pool = new JedisPool(host, port);
try (Jedis jedis = this.pool.getResource()) {
if (password != null && !password.equals("")) {
jedis.auth(password);
}
jedis.select(0);
jedis.close();
}
}
public JedisPool getPool() {
return this.pool;
}
}
Here's my error:
22:16:15 [INFO] [ProxyLink] Attempting to establish Redis connection 127.0.0.1:6379
22:16:15 [WARNING] Exception encountered when loading plugin: ProxyLink
redis.clients.jedis.exceptions.JedisException: Could not return the resource to the pool
at redis.clients.jedis.JedisPool.returnResource(JedisPool.java:106)
at redis.clients.jedis.JedisPool.returnResource(JedisPool.java:12)
at redis.clients.jedis.Jedis.close(Jedis.java:3206)
at me.joeleoli.proxylink.database.RedisDatabase.<init>(RedisDatabase.java:23)
at me.joeleoli.proxylink.ProxyLink.onEnable(ProxyLink.java:71)
at net.md_5.bungee.api.plugin.PluginManager.enablePlugins(PluginManager.java:227)
at net.md_5.bungee.BungeeCord.start(BungeeCord.java:273)
at net.md_5.bungee.BungeeCordLauncher.main(BungeeCordLauncher.java:111)
at net.md_5.bungee.Bootstrap.main(Bootstrap.java:15)
Caused by: redis.clients.jedis.exceptions.JedisException: Could not return the resource to the pool
at redis.clients.util.Pool.returnResourceObject(Pool.java:61)
at redis.clients.jedis.JedisPool.returnResource(JedisPool.java:103)
... 8 more
Caused by: java.lang.IllegalStateException: Object has already been returned to this pool or is invalid
at org.apache.commons.pool2.impl.GenericObjectPool.returnObject(GenericObjectPool.java:551)
at redis.clients.util.Pool.returnResourceObject(Pool.java:59)
... 9 more
The problem with your code is the call to jedis.close() within the try-with-resource block. The try-with-resource block with closes your resource when the block exits. Since you already closed the resource, prior to the block exiting, you end up calling close twice.
Remove the call to jedis.close within the block and just use the try-with-resource functionality.

Creating JDBC transaction for second data source with existing connection pool in Glassfish

I have main data source for working with database, which uses some connection pool. Now I want to create a second data source, which would use the same connection pool to perform logging operations in a separate transaction, then main database transaction! As far as I understood from the Glassfish docs if multiple data sources are using the same connection pool, then they share a transaction until connection is not closed (I might be wrong, please correct me).
So, is there a way to start a new transaction, when getting a connection to a data source? By setting TransactionIsolation may be?
Connection is retrieved in the following way:
private synchronized Connection getConnection() {
if (connection == null) {
try {
final Context ctx = new InitialContext();
final DataSource ds = (DataSource) ctx.lookup(getDataSourceLookupAddress());
connection = ds.getConnection();
} catch (final NamingException e) {
errorHandler.error("Datasource JNDI lookup failed: " + dataSourceLookupAddress + "!");
errorHandler.error(e.toString());
} catch (final SQLException e) {
errorHandler.error("Sql connection failed to " + dataSourceLookupAddress + "!");
errorHandler.error(e.toString());
}
}
return connection;
}
I have figured it out. It's necessary to start a new Thread, then a new transaction will be created. See also Writing to database log in the middle of rollback

Categories