Java調(diào)用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("外網(wǎng)IP", 7003)); nodes.add(new HostAndPort("外網(wǎng)", 7004)); nodes.add(new HostAndPort("外網(wǎng)IP", 7004)); // Jedis連接池配置 JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // 最大空閑連接數(shù), 默認(rèn)8個 jedisPoolConfig.setMaxIdle(100); // 最大連接數(shù), 默認(rèn)8個 jedisPoolConfig.setMaxTotal(500); //最小空閑連接數(shù), 默認(rèn)0 jedisPoolConfig.setMinIdle(0); // 獲取連接時的最大等待毫秒數(shù)(如果設(shè)置為阻塞時BlockWhenExhausted),如果超時就拋異常, 小于零:阻塞不確定的時間, 默認(rèn)-1 jedisPoolConfig.setMaxWaitMillis(2000); // 設(shè)置2秒 //對拿到的connection進行validateObject校驗 jedisPoolConfig.setTestOnBorrow(true); //未設(shè)置auth Password JedisCluster jedis = new JedisCluster(nodes, jedisPoolConfig); //設(shè)置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(); } } }
可能出現(xiàn)的異常
1、DENIED Redis is running in protected mode because protected mode is enabled...
解決方法:redis.conf默認(rèn)禁止外網(wǎng)訪問,修改”protected-mode yes”為“protected-mode no”
2、No more cluster attempts left.
解決方法:redis設(shè)置集群時,服務(wù)器沒有配置開啟集群總線端口(redis端口+10000),如果redis-cli端口有7000-7005,則集群總線端口為17000-17005,服務(wù)器7000-70005、17000-17005端口都要打開
3、No reachable node in cluster
解決方法:查看redis.conf 的 "bind xxxxxxx" 是否限制了IP訪問,注銷bind則可以任意IP訪問服務(wù)器Redis
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
JavaWeb?Listener?利用Session統(tǒng)計在線人數(shù)
這篇文章主要為大家介紹了JavaWeb?Listener?利用Session統(tǒng)計在線人數(shù),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09Java中Future和FutureTask的示例詳解及使用
Java中的Future和FutureTask通常和線程池搭配使用,用來獲取線程池返回執(zhí)行后的返回值,下面這篇文章主要給大家介紹了關(guān)于Java中Future和FutureTask使用的相關(guān)資料,需要的朋友可以參考下2021-11-11Java Springboot websocket使用案例詳解
這篇文章主要介紹了Java Springboot websocket使用案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09