`
raymond.chen
  • 浏览: 1419727 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Redis客户端之Lettuce的使用

 
阅读更多

Lettuce是一个可伸缩的线程安全的Redis客户端,支持同步、异步和响应式模式。多个线程可以共享一个连接实例,而不必担心多线程并发问题。它基于Netty框架构建,支持Redis的高级功能,如Sentinel,集群,流水线,自动重新连接和Redis数据模型。

 

Jedis在实现上是直连Redis-Server,多线程环境下非线程安全,需要通过连接池来使用Jedis。

 

Maven需要添加以下依赖包:

<dependency>
	<groupId>biz.paluch.redis</groupId>
	<artifactId>lettuce</artifactId>
	<version>4.4.6.Final</version>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-pool2</artifactId>
	<version>2.4.3</version>
</dependency>

 

单机版下使用Lettuce

public class CommonTest {
	private static RedisClient client;
	private static GenericObjectPool<StatefulRedisConnection<String, String>> pool;
	
	public static void main(String[] args) {
		open();
		
		//JDK1.7之后有了try-with-resource处理机制。该机制用于自动释放外部资源。
		//被自动释放的资源需要实现Closeable或者AutoCloseable接口,这样JVM才可以自动调用close()方法去自动关闭资源。
		//写法为try(){}catch(){},将要关闭的外部资源在try()中创建,catch()捕获处理异常。

		try(StatefulRedisConnection<String, String> connect = pool.borrowObject()){
			testCommon(connect);
			testList(connect);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}

	private static void testCommon(StatefulRedisConnection<String, String> connect)
			throws InterruptedException, ExecutionException {
		//sync
		RedisCommands<String, String> syncCommand = connect.sync();
		
		//过期
		syncCommand.expire("uid", 60 * 10); //多少秒后过期
		syncCommand.expireat("uid", new Date()); //具体日期到达后过期

		//删除key
		syncCommand.del("auth", "uid", "pwd");
		
		//key是否存在
		System.out.println(syncCommand.exists("uid"));
		
		syncCommand.set("auth", "1");
		
		//批量set
		syncCommand.multi();
		syncCommand.set("uid", "cjm");
		syncCommand.set("pwd", "123");
		syncCommand.exec();
		
		String result = syncCommand.get("uid");
		System.out.println(result);
		
		//async
		RedisAsyncCommands<String, String> asyncCommand = connect.async();
		RedisFuture<Boolean> future = asyncCommand.setnx("uid", "cjm2"); //setnx: key不存在才set
		future.thenAccept(v -> System.out.println(v));
		
		//获取监控信息
		System.out.println(syncCommand.info());
	}
	
	private static void testList(StatefulRedisConnection<String, String> connect){
		RedisCommands<String, String> command = connect.sync();
		
		command.del("colors");
		
		String[] array = {"black", "white", "red", "blue", "yellow"}; //最后一个元素的索引为0
		command.lpush("colors", array); //批量插入元素
		command.lset("colors", 0, "yellow2"); //设置索引为0的元素
		
		System.out.println(command.llen("colors")); //长度
		
		System.out.println(command.lindex("colors", 1)); //取索引为1的元素
		System.out.println(command.lpop("colors")); //取第一个元素,并从List中删除
		System.out.println(command.lastsave().toString()); //最后保存日期
		System.out.println(command.lrange("colors", 2, 2)); //取索引范围的元素
		
		//以流的方式处理
		Long count = command.lrange(new ValueStreamingChannel<String>() {
			@Override
			public void onValue(String value) {
				System.out.println(value);
			}
		}, "colors", 2, 3);
		System.out.println("count=" + count);
	}
	
	private static void open(){
		client = RedisClient.create(RedisURI.create("redis://192.168.134.134:7001"));
		client.setDefaultTimeout(3000, TimeUnit.MILLISECONDS);
		
		//创建连接池
		pool = ConnectionPoolSupport
			.createGenericObjectPool(() -> client.connect(), new GenericObjectPoolConfig());
	}
	
	private static void close(){
		pool.close();
		client.shutdown();
	}
}

 

集群环境下使用Lettuce:

public class ClusterTest {
	private static RedisClusterClient client;
	private static GenericObjectPool<StatefulRedisClusterConnection<String, String>> pool;
	
	public static void main(String[] args) {
		open();
		
        try(StatefulRedisClusterConnection<String, String> connect = pool.borrowObject()){ //获得池对象
        	RedisAdvancedClusterCommands<String, String> syncCommand = connect.sync();
    		syncCommand.set("uid", "cjm");
    		String result = syncCommand.get("uid");
    		System.out.println(result);
    		
    		//归还池的对象
    		pool.returnObject(connect);
    		
        }catch(Exception ex){
        	ex.printStackTrace();
        }finally{
        	close();
        }
	}
	
	private static void open(){
		ArrayList<RedisURI> list = new ArrayList<>();  
        list.add(RedisURI.create("redis://192.168.134.134:7001"));
        list.add(RedisURI.create("redis://192.168.134.134:7002"));
        list.add(RedisURI.create("redis://192.168.134.134:7003"));
        
        client = RedisClusterClient.create(list);
        
        pool = ConnectionPoolSupport
        	.createGenericObjectPool(() -> client.connect(), new GenericObjectPoolConfig());
	}
	
	private static void close(){
        pool.close();
		client.shutdown();
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics