lettuce-core连接redis集群示例代码



import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Map;

import io.lettuce.core.RedisURI;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;

/**
 * Use Lettuce as client to access Redis. <br/>
 * https://lettuce.io/docs/getting-started.html <br />
 *
 * @author zxc
 *
 */
public class RedisClusterUtil
{
	
	private static class Helper
	{
		private static final String KEY_SCHEMA = "yourProject:{0}";
		
		static RedisClusterClient redisClient;
		
		static StatefulRedisClusterConnection<String, String> connection;
		
		static final MessageFormat KEY_FORMAT = new MessageFormat(KEY_SCHEMA);
		
		static
		{
			Runtime.getRuntime().addShutdownHook(new Thread()
			{
				public void run()
				{
					if (connection != null)
					{
						connection.close();
					}
					if (redisClient != null)
					{
						redisClient.shutdown();
					}
					System.out.println("redisClient shutdown in jvmHook.");
				}
			});
		}

		public static void init(Iterable<RedisURI> seed)
		{
			redisClient = RedisClusterClient.create(seed);
			ClusterClientOptions clientOptions = ClusterClientOptions.builder().autoReconnect(true).build();;
			redisClient.setOptions(clientOptions);
			connection = redisClient.connect();
			
			System.out.println("==> Connected to Redis");
		}
		
	}

	public static void init(Iterable<RedisURI> seed) {
		 Helper.init(seed);
	}
	public static String getKey(String value)
	{
		return Helper.KEY_FORMAT.format(new String[] {value});
	}
	
	/**
	 * save the expiration value if more than stored value.
	 * 
	 * @param key key
	 * @param value value
	 * @param expireTime expire time in seconds.
	 */
	public static String set(String key, String value, long expireTime)
	{
		RedisAdvancedClusterCommands<String, String> commands = Helper.connection.sync();
		return commands.setex(getKey(key), expireTime, value);
	}
	
	/**
	 * 默认失效时间
	 */
	private static long defaultExpireTime = 3600 * 24 * 3;
	
	public static String set(String key, String value)
	{
		RedisAdvancedClusterCommands<String, String> commands = Helper.connection.sync();
		return commands.setex(getKey(key), defaultExpireTime, value);
	}
	

	public static String sets(Map<String, String> keyVals)
	{
		if (keyVals == null || keyVals.isEmpty())
		{
			return "Empty Parameters";
		}
		
		return Helper.connection.sync().mset(keyVals);
	}
	
	public static String get(String key)
	{
		String keyWithProjectName = getKey(key);
		String value = Helper.connection.sync().get(keyWithProjectName);
		return value;
	}
	
	/**
	 * 是否存在key
	 * 
	 * @param key 未格式化不包含ETL头的key
	 * @return
	 */
	public static boolean exists(String key)
	{
		// 若 key 存在返回 1 ,否则返回 0
		return 1 == Helper.connection.sync().exists(getKey(key));
	}
	
	public static Long del(String key)
	{
		String keyWithProjectName = getKey(key);
		return Helper.connection.sync().del(keyWithProjectName);
	}
	
	/**
	 * 删除多个key,key需要自己加上前置
	 * 
	 * @param keys
	 * @return
	 */
	public static Long dels(String... keys)
	{
		if (keys == null || keys.length == 0)
		{
			return 0L;
		}
		return Helper.connection.sync().del(keys);
	}
	
	private RedisClusterUtil()
	{
		
	}
	
	public static void main(String[] args)
		throws Exception
	{
		ArrayList<RedisURI> seed = new ArrayList<>();
		RedisURI uri = RedisURI.builder()
			.withHost("192.168.110.110")
			.withPort(6379)
			// .withPassword(password)
			// .withSsl(true)
			.build();
		seed.add(uri);
		RedisClusterUtil.init(seed);
		
		
		String key = "1:2:3";
		String value = "<obj><id>1</id></obj>";
		
		MessageFormat KEY_FORMAT = new MessageFormat("youProject_{0}") ;
		System.out.println(KEY_FORMAT.format(new String[] {key}));
		System.out.println(RedisClusterUtil.get(key));
		System.out.println(RedisClusterUtil.set(key, value));
		System.out.println(RedisClusterUtil.set(key, value, 3));
		System.out.println(RedisClusterUtil.get(key));
		System.out.println(RedisClusterUtil.exists(key));
		System.out.println(RedisClusterUtil.del(key));
		System.out.println(RedisClusterUtil.exists(key));
		System.out.println(RedisClusterUtil.get(key));
	}
}

参考:

lettuce-core/ConnectToRedisCluster.java at 5.3.1.RELEASE · lettuce-io/lettuce-core · GitHub

Lettuce - Getting Started

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中,使用 Lettuce 连接 Redis 时,可以通过自适应配置来适配单机版 Redis 和集群版 Redis。自适应配置是指,当配置文件中的属性值符合某种特定的格式时,Lettuce 会自动识别当前 Redis 环境是否为集群版,并自动进行相应的连接池配置。 具体来说,当 `spring.redis.host` 属性为空时,Lettuce 将会按照集群版 Redis 的方式进行连接。此时,需要在 `spring.redis.cluster.nodes` 属性中指定 Redis 集群中所有节点的地址和端口号,以逗号分隔。例如: ```properties # Redis 自适应集群版连接池配置 spring.redis.host= spring.redis.port= spring.redis.password=your_password spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381 spring.redis.timeout=1000 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-wait=-1 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0 ``` 当 `spring.redis.host` 属性不为空时,Lettuce 将会按照单机版 Redis 的方式进行连接。此时,只需要在 `spring.redis.host` 和 `spring.redis.port` 属性中指定 Redis 服务器的地址和端口号即可。例如: ```properties # Redis 自适应单机版连接池配置 spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=your_password spring.redis.timeout=1000 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-wait=-1 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0 ``` 需要注意的是,当 `spring.redis.host` 属性为空时,必须同时指定 `spring.redis.cluster.nodes` 属性,否则会抛出异常。此外,当使用自适应配置连接集群版 Redis 时,需要在 `pom.xml` 文件中添加 Lettuce 依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> <version>5.3.4.RELEASE</version> </dependency> ``` 以上就是在 Spring Boot 中使用 Lettuce 进行自适应配置连接单机版 Redis 和集群版 Redis 的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值