问题
Is there a way to connect to the Redis Cache Cluster Node by providing the Node endpoint? Which library should I use for this?
Also, which API should I use to store and retrieve contents from the Cache?
回答1:
In short
It depends.
Explanation
You can connect to Redis Cluster nodes without command dispatching to other nodes. You just should make sure, that you access keys that are handled by the node. If you are connecting to a slave make sure, that your connection is in READONLY
mode, otherwise the slave will respond with MOVED
.
There are plenty of Java-based Redis Clients:
Low Level
- Jedis - synchronous API
- Lettuce - async and sync API
- SRP
- JRedis
High Level
- Spring Data Redis (uses Jedis, Lettuce and SRP as drivers)
- Redisson
...and many more. You can find a more comprehensive list of Java Redis Clients at http://redis.io/clients#java
Which client should you take?
Well, this depends mostly on your requirements. If you need "just a client" for short-lived connections, then perhaps Jedis is the right choice for you. If you need flexibility, async responses and custom codecs, then lettuce might be your friend.
If you want to deal with Java Collections, Locks and many more, then take a look on Spring Data Redis or Redisson.
Which API should you take?
Depends also on your requirements. The Redis protocol might be more flexible than the memcached protocol since Redis supports more data structures.
HTH, Mark
回答2:
Basic Redis commands class:
import java.util.Set;
import java.util.ArrayList;
import redis.clients.jedis.Jedis;
public class RedisConnection
{
private Jedis jedis;
private String hostNameIp;
public RedisConnection()
{
//Set hostNameIp using properties file/directly(shown below):
this.hostNameIp="HOSTNAME_IP";
this.jedis=new Jedis(hostNameIp);
this.jedis=getConnection(hostNameIp);
}
private Jedis getConnection(String hostNameIp)
{
jedis.connect();
return jedis;
}
public ArrayList<String> getAvailableKeys()
{
Set<String> dataFromRedis=jedis.keys("*");
ArrayList<String> dataFromRedisAsArrayList=new ArrayList<String>(dataFromRedis);
jedis.close();
return dataFromRedisAsArrayList;
}
public String getValueByName(String keyName)
{
String valueOfKey=jedis.get(keyName);
jedis.close();
return valueOfKey;
}
public void flushAvailableKeys()
{
jedis.flushAll();
jedis.close();
}
}
Calling the method(getting data from redis)
RedisConnection redisConnection=new RedisConnection();
ArrayList<String> dataInRedis=redisConnection.getAvailableKeys();
来源:https://stackoverflow.com/questions/30878431/java-client-to-connect-elasticcache-redis-cache-node