maven导入jedis包:

		<dependency>
		    <groupId>redis.clients</groupId>
		    <artifactId>jedis</artifactId>
		    <version>3.7.0</version>
		</dependency>

搭建redis哨兵模式:Redis——sentinel哨兵模式_FlyLikeButterfly的博客-CSDN博客

ip:192.168.1.31;

主:192.168.1.31:6379;从1:192.168.1.31:6380;从2:192.168.1.31:6381:

哨兵1:192.168.1.31:26379;哨兵2:192.168.1.31:26380;哨兵3:192.168.1.31:26381;

测试Demo:

/**
 * 2021年11月8日上午9:56:21
 */
package testJedisSentinel;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

/**
 * @author XWF
 *
 */
public class TestJedisSentinel {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Set<String> sentinels = new HashSet<>();
		sentinels.add("192.168.1.31:26379");
		sentinels.add("192.168.1.31:26380");
		sentinels.add("192.168.1.31:26381");
		GenericObjectPoolConfig<Jedis> poolConfig = new GenericObjectPoolConfig<>();
		poolConfig.setMaxIdle(100);
		poolConfig.setMaxWaitMillis(10000);
		poolConfig.setTestOnBorrow(true);
		int connectionTimeout = 5000;
		int soTimeout = 5000;
		String password = "654321";
		int database = 0;
		try (JedisSentinelPool jspool = new JedisSentinelPool("mymaster", sentinels, poolConfig, 
				connectionTimeout, soTimeout, password, database)) {
			Jedis jedis = jspool.getResource();
			jedis.mset("a", "AAA", "b", "BBB");
			System.out.println(jedis.get("a"));
			System.out.println(jedis.get("b"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

结果:

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐