Jedis连接Redis三种方式

1、单机模式

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));
2、分片模式

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);
3、集群模式(since 3.0)

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) ;
4. JedisUtil

从jedis 3.0.1之后,jedis使用完毕后调用jedis.close()来归还连接,其内部调用的仍然是return resource和returnBrokenResource

public class RedisUtils {
private JedisPool jedisPool;
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 returnJedis(Jedis jedis) {
if (jedis != null) {
//释放资源
jedis.close(http://www.my516.com);

}
}
}
 
---------------------

posted @ 2019-07-10 01:02  水至清明  阅读(4999)  评论(0编辑  收藏  举报