前言 需要使用以下jar包 Maven项目引用以下配置: dependency groupIdorg.apache.commons/groupId artifactIdcommons-pool2/artifactId version2.6.2/version/dependency dependency groupIdredis.clients/groupId artifactIdjedis/artifac
前言
需要使用以下jar包
Maven项目引用以下配置:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.6.2</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.0.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.26</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> <version>1.7.26</version> <scope>test</scope> </dependency>
代码
package Main;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.Set;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
@SuppressWarnings("all")
public class RedisMain {
public static void main(String[] args) {
JedisCluster cluster =null;
try {
Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
//一般选用slaveof从IP+端口进行增删改查,不用master
nodes.add(new HostAndPort("外网IP", 7003));
nodes.add(new HostAndPort("外网", 7004));
nodes.add(new HostAndPort("外网IP", 7004));
// Jedis连接池配置
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// 最大空闲连接数, 默认8个
jedisPoolConfig.setMaxIdle(100);
// 最大连接数, 默认8个
jedisPoolConfig.setMaxTotal(500);
//最小空闲连接数, 默认0
jedisPoolConfig.setMinIdle(0);
// 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1
jedisPoolConfig.setMaxWaitMillis(2000); // 设置2秒
//对拿到的connection进行validateObject校验
jedisPoolConfig.setTestOnBorrow(true);
//未设置auth Password
JedisCluster jedis = new JedisCluster(nodes, jedisPoolConfig);
//设置auth Password
//JedisCluster jedis = new JedisCluster(nodes,5000,3000,10,{auth_password}, new JedisPoolConfig());
System.out.println(jedis.get("mykey"));
}catch(Exception e) {
e.printStackTrace();
}finally {
if(null !=cluster)
cluster.close();
}
}
}
可能出现的异常
1、DENIED Redis is running in protected mode because protected mode is enabled...
解决方法:redis.conf默认禁止外网访问,修改”protected-mode yes”为“protected-mode no”
2、No more cluster attempts left.
解决方法:redis设置集群时,服务器没有配置开启集群总线端口(redis端口+10000),如果redis-cli端口有7000-7005,则集群总线端口为17000-17005,服务器7000-70005、17000-17005端口都要打开
3、No reachable node in cluster
解决方法:查看redis.conf 的 "bind xxxxxxx" 是否限制了IP访问,注销bind则可以任意IP访问服务器Redis
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。
