当前位置: 首页 > 工具软件 > lettuce-core > 使用案例 >

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

相俊迈
2023-12-01


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

 类似资料: