这篇文章给大家介绍如何在Java项目中调用Redis集群,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
前言
需要使用以下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
关于如何在Java项目中调用Redis集群就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。