这里说的三种工作模式是指:
1、单机模式
2、分片模式
3、集群模式(since 3.0)
说明图详见以下:
使用单机模式连接:
private String addr="192.168.1.1";
private String port="6236";
private String key="key";
private Jedis jedis=new Jedis(addr,port);//Jedis获取到的Redis数据在jedis里,
jedis.set("a","b");//更改key为a的值
jedis.hmset(key,hash);
System.out.println(jedis.get(key));
使用分片模式连接:
GenericObjectPoolConfig config=new GenericObjectPoolConfig();
config.setMaxIdle(32);
config.setMinIdle(12);
config.setTestOnBorrow(true);
config.setTestOnReturn(rtrue);
config.setTestWhileIdle(true);
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
for (int i = 0; i < shareds.size(); i++) {
shards.add(new JedisShardInfo("192.168.0.100", 6379, 200));
}
// 构造池
ShardedJedisPool shardedJedisPool= new ShardedJedisPool(config, shards);
ShardedJedis jedis=shardedJedisPool.getResource();
jedis.set("a","b");
jedis.hmset(key, hash);
使用集群模式:
String[] ADDRs = conf.getString("redisIP", "10.244.84.33").split(",");//conf是读取的配置
String[] PORTs = conf.getString("redisPort", "6379").split(",");
for (int i = 0; i < length; i++) {
HostAndPort hostAndPort = new HostAndPort(ADDRs[i], Integer.parseInt(PORTs[i]));
haps.add(hostAndPort);
}
JedisCluster myJedisCluster = new JedisCluster(haps, TIMEOUT);
Map<String, String> gather = new HashMap<>(); //Redis中的数据是<key,value>形式,也可以是其他类型的数据
gather =myJedisCluster.hgetAll(key) ;
补充:使用JedisPool连接Redis:
public class RedisUtils {
static { String configurationFileName = "xxx.properties";
Configuration conf = Configuration.getConfiguration(configurationFileName);
if (conf == null) {
System.out.println("reading " + configurationFileName + " is failed.");
System.exit(-1);
}
String[] ADDRs = conf.getString("redisIP", "10.100.56.33").split(",");
String[] PORTs = conf.getString("redisPort", "6379").split(","); if (ADDRs.length == 0 || PORTs.length == 0) {
System.out.println("definition redisIP is not found in " + configurationFileName);
System.exit(-1);
}
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(MAX_IDLE);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, ADDRs[0], PORT, TIMEOUT);
} public synchronized static Jedis getJedis() {
if (jedisPool != null) {
//获取资源
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} public static void returnBrokenResource(Jedis jedis) {
if (jedis != null) {
//释放资源
jedisPool.returnBrokenResource(jedis); }
} public static void returnResource(Jedis jedis) {
if (jedis != null) {
//释放资源
jedisPool.returnResource(jedis);
}
}
}
尚有需要改进之处,暂时记录一下