Lettuce操作redis

2023-12-22 07:12
文章标签 操作 redis lettuce

本文主要是介绍Lettuce操作redis,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Lettuce是一个高性能基于Java编写的Redis驱动框架,底层集成了Project Reactor提供天然的反应式编程,通信框架集成了Netty使用了非阻塞IO,5.x版本之后融合了JDK1.8的异步编程特性,在保证高性能的同时提供了十分丰富易用的API。本文主要介绍使用lettuce操作redis,使用到的软件版本:Java 1.8.0_191、Redis 5.0.8、lettuce 5.3.1.RELEASE。

1、引入依赖

<dependency><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId><version>5.3.1.RELEASE</version>
</dependency>
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.8.0</version>
</dependency>

2、基本操作

package com.shangjack.redis;import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.SetArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import io.lettuce.core.api.reactive.RedisReactiveCommands;
import io.lettuce.core.api.sync.RedisCommands;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import reactor.core.publisher.Mono;import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.Future;/*** 使用Lettuce操作redis*/
public class LettuceBaseCase {private static RedisClient client;private StatefulRedisConnection<String, String> connection;    @Beforepublic void before() {RedisURI redisUri = RedisURI.builder().withHost("10.49.196.10").withPort(6379).withPassword("123456").withTimeout(Duration.of(10, ChronoUnit.SECONDS)).build();client = RedisClient.create(redisUri);connection = client.connect();}    @Afterpublic void after() {connection.close();client.shutdown();}/*** 同步操作* apijedis很类型*/
    @Testpublic void sync() {RedisCommands<String, String> commands = connection.sync();String result = commands.set("name", "mayun");System.out.println(result);SetArgs args = SetArgs.Builder.nx().ex(10);result = commands.set("age", "30", args);System.out.println(result);}/*** 异步操作*/
    @Testpublic void async() throws Exception {RedisAsyncCommands<String, String> commands = connection.async();Future<String> future = commands.set("name", "mayun");System.out.println(future.get());SetArgs args = SetArgs.Builder.nx().ex(10);future = commands.set("age", "30", args);System.out.println(future.get());}/*** 响应式API*/
    @Testpublic void reactive() throws Exception {RedisReactiveCommands<String, String> commands = connection.reactive();Mono<String> result = commands.set("name", "mayun");System.out.println(result.block());SetArgs args = SetArgs.Builder.nx().ex(10);result = commands.set("age", "30", args);result.subscribe(value -> System.out.println(value));//开启一个事务,先把counter设置为1,再将counter自增1commands.multi().doOnSuccess(r -> {commands.set("count", "1").doOnNext(System.out::println).subscribe();commands.incr("count").doOnNext(c -> System.out.println(c)).subscribe();}).flatMap(s -> commands.exec()).doOnNext(transactionResult -> System.out.println(transactionResult.wasDiscarded())).subscribe();Thread.sleep(1000 * 5);}}

3、高级操作

package com.shangjack.redis;import io.lettuce.core.ClientOptions;
import io.lettuce.core.ReadFrom;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
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.Executions;
import io.lettuce.core.cluster.api.sync.NodeSelection;
import io.lettuce.core.cluster.api.sync.NodeSelectionCommands;
import io.lettuce.core.cluster.api.sync.RedisAdvancedClusterCommands;
import io.lettuce.core.codec.StringCodec;
import io.lettuce.core.masterreplica.MasterReplica;
import io.lettuce.core.masterreplica.StatefulRedisMasterReplicaConnection;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import io.lettuce.core.support.ConnectionPoolSupport;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.junit.Test;import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.*;/*** 高级操作*/
public class LettuceAdvanceCase {/*** 主从模式操作*/
    @Testpublic void masterSlave() {//这里只需要配置一个节点的连接信息,不一定需要是主节点的信息,从节点也可以;可以自动发现主从节点RedisURI uri = RedisURI.builder().withHost("10.16.60.42").withPort(6379).withPassword("123456").build();RedisClient client = RedisClient.create(uri);StatefulRedisMasterReplicaConnection<String, String> connection = MasterReplica.connect(client, StringCodec.UTF8, uri);//从节点读书数据connection.setReadFrom(ReadFrom.REPLICA);RedisCommands<String, String> commands = connection.sync();commands.set("name", "刘备");System.out.println(commands.get("name"));connection.close();client.shutdown();}/*** 主从模式操作2*/
    @Testpublic void masterSlave2() {List<RedisURI> uris = new ArrayList();uris.add(RedisURI.builder().withHost("10.16.60.42").withPort(6379).withPassword("123456").build());uris.add(RedisURI.builder().withHost("10.16.60.43").withPort(6379).withPassword("123456").build());uris.add(RedisURI.builder().withHost("10.16.60.44").withPort(6379).withPassword("123456").build());RedisClient client = RedisClient.create();StatefulRedisMasterReplicaConnection<String, String> connection = MasterReplica.connect(client, StringCodec.UTF8, uris);//从节点读书数据connection.setReadFrom(ReadFrom.REPLICA);RedisCommands<String, String> commands = connection.sync();commands.set("name", "张飞");System.out.println(commands.get("name"));connection.close();client.shutdown();}/*** 哨兵模式操作*/
    @Testpublic void sentinel() {List<RedisURI> uris = new ArrayList();uris.add(RedisURI.builder().withSentinel("10.16.60.42", 26379).withSentinelMasterId("mymaster").withPassword("123456").build());uris.add(RedisURI.builder().withSentinel("10.16.60.43", 26379).withSentinelMasterId("mymaster").withPassword("123456").build());uris.add(RedisURI.builder().withSentinel("10.16.60.44", 26379).withSentinelMasterId("mymaster").withPassword("123456").build());RedisClient client = RedisClient.create();StatefulRedisMasterReplicaConnection<String, String> connection = MasterReplica.connect(client, StringCodec.UTF8, uris);//从节点读书数据connection.setReadFrom(ReadFrom.REPLICA);RedisCommands<String, String> commands = connection.sync();commands.set("name", "赵云");System.out.println(commands.get("name"));connection.close();client.shutdown();}/*** 集群操作*/
    @Testpublic void cluster() {Set<RedisURI> uris = new HashSet<>();uris.add(RedisURI.builder().withHost("10.16.60.42").withPort(7000).withPassword("123456").build());uris.add(RedisURI.builder().withHost("10.16.60.42").withPort(7001).withPassword("123456").build());uris.add(RedisURI.builder().withHost("10.16.60.43").withPort(7000).withPassword("123456").build());uris.add(RedisURI.builder().withHost("10.16.60.43").withPort(7001).withPassword("123456").build());uris.add(RedisURI.builder().withHost("10.16.60.44").withPort(7000).withPassword("123456").build());uris.add(RedisURI.builder().withHost("10.16.60.44").withPort(7001).withPassword("123456").build());RedisClusterClient client = RedisClusterClient.create(uris);StatefulRedisClusterConnection<String, String> connection = client.connect();RedisAdvancedClusterCommands<String, String> commands = connection.sync();commands.set("name", "关羽");System.out.println(commands.get("name"));//选择从节点,只读NodeSelection<String, String> replicas = commands.replicas();NodeSelectionCommands<String, String> nodeSelectionCommands = replicas.commands();Executions<List<String>> keys = nodeSelectionCommands.keys("*");keys.forEach(key -> System.out.println(key));connection.close();client.shutdown();}/*** 配置客户端资源(ClientResources)及客户端参数(ClientOptions)*/
    @Testpublic void resourceAndOption() {ClientResources resources = DefaultClientResources.builder().ioThreadPoolSize(4) //I/O线程数.computationThreadPoolSize(4) //任务线程数.build();RedisURI redisUri = RedisURI.builder().withHost("10.49.196.10").withPort(6379).withPassword("123456").withTimeout(Duration.of(10, ChronoUnit.SECONDS)).build();ClientOptions options = ClientOptions.builder().autoReconnect(true)//是否自动重连.pingBeforeActivateConnection(true)//连接激活之前是否执行PING命令.build();RedisClient client = RedisClient.create(resources, redisUri);client.setOptions(options);StatefulRedisConnection<String, String> connection = client.connect();RedisCommands<String, String> commands = connection.sync();System.out.println(commands.get("name"));connection.close();client.shutdown();resources.shutdown();}/*** 配置客户端资源(ClientResources)及客户端参数(ClientOptions)* 集群*/
    @Testpublic void resourceAndOption2() {ClientResources resources = DefaultClientResources.builder().ioThreadPoolSize(4) //I/O线程数.computationThreadPoolSize(4) //任务线程数.build();//集群地址,配置其中一个即可,不需要配置全RedisURI redisUri = RedisURI.builder().withHost("10.16.60.42").withPort(7000).withPassword("123456").withTimeout(Duration.of(10, ChronoUnit.SECONDS)).build();ClusterClientOptions options = ClusterClientOptions.builder().autoReconnect(true)//是否自动重连.pingBeforeActivateConnection(true)//连接激活之前是否执行PING命令.validateClusterNodeMembership(true)//是否校验集群节点的成员关系.build();RedisClusterClient client = RedisClusterClient.create(resources, redisUri);client.setOptions(options);StatefulRedisClusterConnection<String, String> connection = client.connect();RedisAdvancedClusterCommands<String, String> commands = connection.sync();System.out.println(commands.get("name"));connection.close();client.shutdown();resources.shutdown();}/*** 连接池*/
    @Testpublic void pool() throws Exception {RedisURI redisUri = RedisURI.builder().withHost("10.49.196.10").withPort(6379).withPassword("123456").withTimeout(Duration.of(10, ChronoUnit.SECONDS)).build();RedisClient client = RedisClient.create(redisUri);GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport.createGenericObjectPool(client::connect, poolConfig);StatefulRedisConnection<String, String> connection = pool.borrowObject();RedisCommands<String, String> commands = connection.sync();System.out.println(commands.get("name"));connection.close();pool.close();client.shutdown();}}

这篇关于Lettuce操作redis的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/523026

相关文章

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

动手学深度学习【数据操作+数据预处理】

import osos.makedirs(os.path.join('.', 'data'), exist_ok=True)data_file = os.path.join('.', 'data', 'house_tiny.csv')with open(data_file, 'w') as f:f.write('NumRooms,Alley,Price\n') # 列名f.write('NA

线程的四种操作

所属专栏:Java学习        1. 线程的开启 start和run的区别: run:描述了线程要执行的任务,也可以称为线程的入口 start:调用系统函数,真正的在系统内核中创建线程(创建PCB,加入到链表中),此处的start会根据不同的系统,分别调用不同的api,创建好之后的线程,再单独去执行run(所以说,start的本质是调用系统api,系统的api

Java IO 操作——个人理解

之前一直Java的IO操作一知半解。今天看到一个便文章觉得很有道理( 原文章),记录一下。 首先,理解Java的IO操作到底操作的什么内容,过程又是怎么样子。          数据来源的操作: 来源有文件,网络数据。使用File类和Sockets等。这里操作的是数据本身,1,0结构。    File file = new File("path");   字

Redis中使用布隆过滤器解决缓存穿透问题

一、缓存穿透(失效)问题 缓存穿透是指查询一个一定不存在的数据,由于缓存中没有命中,会去数据库中查询,而数据库中也没有该数据,并且每次查询都不会命中缓存,从而每次请求都直接打到了数据库上,这会给数据库带来巨大压力。 二、布隆过滤器原理 布隆过滤器(Bloom Filter)是一种空间效率很高的随机数据结构,它利用多个不同的哈希函数将一个元素映射到一个位数组中的多个位置,并将这些位置的值置

MySQL——表操作

目录 一、创建表 二、查看表 2.1 查看表中某成员的数据 2.2 查看整个表中的表成员 2.3 查看创建表时的句柄 三、修改表 alter 3.1 重命名 rename 3.2 新增一列 add 3.3 更改列属性 modify 3.4 更改列名称 change 3.5 删除某列 上一篇博客介绍了库的操作,接下来来看一下表的相关操作。 一、创建表 create

Lua 脚本在 Redis 中执行时的原子性以及与redis的事务的区别

在 Redis 中,Lua 脚本具有原子性是因为 Redis 保证在执行脚本时,脚本中的所有操作都会被当作一个不可分割的整体。具体来说,Redis 使用单线程的执行模型来处理命令,因此当 Lua 脚本在 Redis 中执行时,不会有其他命令打断脚本的执行过程。脚本中的所有操作都将连续执行,直到脚本执行完成后,Redis 才会继续处理其他客户端的请求。 Lua 脚本在 Redis 中原子性的原因

封装MySQL操作时Where条件语句的组织

在对数据库进行封装的过程中,条件语句应该是相对难以处理的,毕竟条件语句太过于多样性。 条件语句大致分为以下几种: 1、单一条件,比如:where id = 1; 2、多个条件,相互间关系统一。比如:where id > 10 and age > 20 and score < 60; 3、多个条件,相互间关系不统一。比如:where (id > 10 OR age > 20) AND sco

laravel框架实现redis分布式集群原理

在app/config/database.php中配置如下: 'redis' => array('cluster' => true,'default' => array('host' => '172.21.107.247','port' => 6379,),'redis1' => array('host' => '172.21.107.248','port' => 6379,),) 其中cl

PHP7扩展开发之流操作

前言 啥是流操作?简单来讲就是对一些文件,网络的IO操作。PHP已经把这些IO操作,封装成流操作。这节,我们将使用PHP扩展实现一个目录遍历的功能。PHP示例代码如下: <?phpfunction list_dir($dir) {if (is_dir($dir) === false) {return;} $dh = opendir($dir);if ($dh == false) {ret