Redis 之 客户端框架比较:Jedis,Redisson,Lettuce

三者区别参考:

Redis 客户端 Jedis、lettuce 和 Redisson 对比 - 程序员自由之路 - 博客园

Redis 之 客户端框架比较:Jedis,Redisson,Lettuce - 如梦灬遗忘 - 博客园

redis比较推荐用法是:Redisson + Lettuce

Redisson:主要用分布式锁

Lettuce:redis的基本功能,各种类型的数据类型的操作

依赖如下:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><version>2.3.12.RELEASE</version>
</dependency><dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>${redisson.version}</version>
</dependency>

实际使用过程中,只需要引入redisson依赖,因为它的依赖中已经包含了Lettuce,如下图:

具体实现:

1.引入依赖

2.配置yaml文件

3.属性配置类

4.初始化RedissonClient客户端

5.初始化各种数据类型bean

6.工具类

1.引入依赖

<dependency><groupId>org.redisson</groupId><artifactId>redisson-spring-boot-starter</artifactId><version>${redisson.version}</version>
</dependency>

2.配置yaml文件

springredis:cluster:nodes: 192.168.106.27:8001,192.168.106.27:8002,192.168.106.27:8003,192.168.106.27:8004,192.168.106.27:8005,192.168.106.27:8006scan-interval: 1000retry-attempts: 3failed-attempts: 3slave-connection-pool-size: 64master-connection-pool-size: 64retry-interval: 1500password: 2021@zgzttimeout: 60000database: 0mode: clusterpool:max-idle: 16min-idle: 8max-active: 8max-wait: 3000conn-timeout: 3000so-timeout: 3000size: 10

3.属性配置类

@Component
@Data
@ConfigurationProperties(prefix = "spring.redis")
public class RedisProperties {private int database;/*** 等待节点回复命令的时间。该时间从命令发送成功时开始计时*/private int timeout;private String password;private String mode;/*** 池配置*/private RedisPoolProperties pool;/*** 集群 信息配置*/private RedisClusterProperties cluster;
}

@Data
public class RedisClusterProperties {/*** 集群状态扫描间隔时间,单位是毫秒*/private int scanInterval;/*** 集群节点*/private String nodes;/*** 默认值: SLAVE(只在从服务节点里读取)设置读取操作选择节点的模式。 可用值为: SLAVE - 只在从服务节点里读取。* MASTER - 只在主服务节点里读取。 MASTER_SLAVE - 在主从服务节点里都可以读取*/private String readMode;/*** (从节点连接池大小) 默认值:64*/private int slaveConnectionPoolSize;/*** 主节点连接池大小)默认值:64*/private int masterConnectionPoolSize;/*** (命令失败重试次数) 默认值:3*/private int retryAttempts;/*** 命令重试发送时间间隔,单位:毫秒 默认值:1500*/private int retryInterval;/*** 执行失败最大次数默认值:3*/private int failedAttempts;}
@Data
public class RedisPoolProperties {private int maxIdle;private int minIdle;private int maxActive;private int maxWait;private int connTimeout;private int soTimeout;/*** 池大小*/private int size;
}

4.初始化RedissonClient客户端

@Configuration
public class RedissonConfig {@Autowiredprivate RedisProperties redisProperties;@Beanpublic Redisson redisson() {//redisson版本是3.5,集群的ip前面要加上“redis://”,不然会报错,3.2版本可不加List<String> clusterNodes = new ArrayList<>();String nodes = redisProperties.getCluster().getNodes();List<String> list = Arrays.asList(nodes.split(",")).stream().map(s -> (s.trim())).collect(Collectors.toList());for (int i = 0; i < list.size(); i++) {clusterNodes.add("redis://" + list.get(i));}Config config = new Config();ClusterServersConfig clusterServersConfig = config.useClusterServers().addNodeAddress(clusterNodes.toArray(new String[clusterNodes.size()]));clusterServersConfig.setPassword(redisProperties.getPassword());//设置密码return (Redisson) Redisson.create(config);}/*** 集群模式的 redisson 客户端** @return*/@Bean@ConditionalOnProperty(name = "spring.redis.mode", havingValue = "cluster")public RedissonClient redissonClient() {System.out.println("cluster redisProperties:" + redisProperties.getCluster());Config config = new Config();String[] nodes = redisProperties.getCluster().getNodes().split(",");List<String> newNodes = new ArrayList(nodes.length);Arrays.stream(nodes).forEach((index) -> newNodes.add(index.startsWith("redis://") ? index : "redis://" + index));ClusterServersConfig serverConfig = config.useClusterServers().addNodeAddress(newNodes.toArray(new String[0])).setScanInterval(redisProperties.getCluster().getScanInterval()).setIdleConnectionTimeout(redisProperties.getPool().getSoTimeout()).setConnectTimeout(redisProperties.getPool().getConnTimeout()).setRetryAttempts(redisProperties.getCluster().getRetryAttempts()).setRetryInterval(redisProperties.getCluster().getRetryInterval()).setMasterConnectionPoolSize(redisProperties.getCluster().getMasterConnectionPoolSize()).setSlaveConnectionPoolSize(redisProperties.getCluster().getSlaveConnectionPoolSize()).setTimeout(redisProperties.getTimeout());if (StringUtils.isNotBlank(redisProperties.getPassword())) {serverConfig.setPassword(redisProperties.getPassword());}return Redisson.create(config);}}

5.初始化各种数据类型bean

@Configuration
@Component
public class RedisConfig {@Resourceprivate RedisConnectionFactory factory;public RedisConfig() {}@Beanpublic RedisTemplate<String, Object> redisTemplate() {RedisTemplate<String, Object> redisTemplate = new RedisTemplate();redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(new StringRedisSerializer());redisTemplate.setConnectionFactory(this.factory);return redisTemplate;}@Beanpublic HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {return redisTemplate.opsForHash();}@Beanpublic ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {return redisTemplate.opsForValue();}@Beanpublic ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {return redisTemplate.opsForList();}@Beanpublic SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {return redisTemplate.opsForSet();}@Beanpublic ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {return redisTemplate.opsForZSet();}
}

6.工具类

@Component
public class RedisUtils {@Resourceprivate RedisTemplate<String, Object> redisTemplate;@Resourceprivate ValueOperations<String, String> valueOperations;@Resourceprivate HashOperations<String, String, Object> hashOperations;@Resourceprivate ListOperations<String, Object> listOperations;@Resourceprivate SetOperations<String, Object> setOperations;@Resourceprivate ZSetOperations<String, Object> zSetOperations;@Resourceprivate StringRedisTemplate stringRedisTemplate;public RedisUtils() {}public boolean exists(String key) {return this.redisTemplate.hasKey(key);}public void set(String key, Object value, long expire) {this.valueOperations.set(key, JsonUtils.toJson(value));if (expire != -1L) {this.expire(key, expire, TimeUnit.SECONDS);}}public void set(String key, Object value) {this.set(key, value, -1L);}public void expire(String key, long time, TimeUnit timeUnit) {this.redisTemplate.expire(key, time, timeUnit);}public void expireKeyAt(String key, Date date) {this.redisTemplate.expireAt(key, date);}public long getKeyExpire(String key, TimeUnit timeUnit) {return this.redisTemplate.getExpire(key, timeUnit);}public void persistKey(String key) {this.redisTemplate.persist(key);}public <T> T get(String key, Class<T> clazz, long expire) {String value = (String) this.valueOperations.get(key);if (expire != -1L) {this.expire(key, expire, TimeUnit.SECONDS);}return value == null ? null : JsonUtils.fromJson(value, clazz);}public JSONObject getJsonObject(String key, long expire) {String value = (String) this.valueOperations.get(key);if (expire != -1L) {this.expire(key, expire, TimeUnit.SECONDS);}return value == null ? null : JsonUtils.fromJson(value);}public JSONArray getJsonArray(String key, long expire) {String value = (String) this.valueOperations.get(key);if (expire != -1L) {this.expire(key, expire, TimeUnit.SECONDS);}return value == null ? null : JsonUtils.fromJsonArray(value);}public <T> T get(String key, Class<T> clazz) {return this.get(key, clazz, -1L);}public JSONObject getJsonObject(String key) {return this.getJsonObject(key, -1L);}public JSONArray getJsonArray(String key) {return this.getJsonArray(key, -1L);}public String get(String key, long expire) {String value = (String) this.valueOperations.get(key);if (expire != -1L) {this.expire(key, expire, TimeUnit.SECONDS);}return value;}public Integer valueAppend(String key, String value) {return this.valueOperations.append(key, value);}public Double incrByDouble(String key, double increment) {return this.valueOperations.increment(key, increment);}public Long incrBy(String key, long increment) {return this.valueOperations.increment(key, increment);}public void setByMap(Map<String, String> valueMap) {this.valueOperations.multiSetIfAbsent(valueMap);}public void setMap(Map<String, String> valueMap) {this.valueOperations.multiSet(valueMap);}public Long getSize(String key) {return this.valueOperations.size(key);}public boolean setIfAbsent(String key, String value) {return this.valueOperations.setIfAbsent(key, value);}public boolean setIfAbsent(String key, String value, long l, TimeUnit timeUnit) {return this.valueOperations.setIfAbsent(key, value, l, timeUnit);}public boolean setIfPresent(String key, String value) {return this.valueOperations.setIfPresent(key, value);}public boolean setIfPresent(String key, String value, long l, TimeUnit timeUnit) {return this.valueOperations.setIfPresent(key, value, l, timeUnit);}public String get(String key) {return this.get(key, -1L);}public void delete(String key) {this.redisTemplate.delete(key);}public void delete(String... keys) {Set<String> kSet = (Set) Stream.of(keys).map((k) -> {return k;}).collect(Collectors.toSet());this.redisTemplate.delete(kSet);}public void delete(Collection<String> keys) {Set<String> kSet = (Set) keys.stream().map((k) -> {return k;}).collect(Collectors.toSet());this.redisTemplate.delete(kSet);}public void renameKey(String oldKey, String newKey) {this.redisTemplate.rename(oldKey, newKey);}public void setOperationsAdd(String key, Object value, long expire) {this.setOperations.add(key, new Object[] { value });if (expire != -1L) {this.expire(key, expire, TimeUnit.SECONDS);}}public void setOperationsAdd(String key, Object value) {this.setOperationsAdd(key, value, -1L);}public Set setOperationsMembers(String key) {return this.setOperations.members(key);}public boolean setOperationsIsMembers(String key, Object value) {return this.setOperations.isMember(key, value);}public Long setOperationsRemove(String key, Object value) {return this.setOperations.remove(key, new Object[] { value });}public boolean hashKey(String key, String hashKey) {return this.hashOperations.hasKey(key, hashKey);}public void hashPut(String key, String hashKey, Object domain) {this.hashPutObject(key, hashKey, JsonUtils.toJson(domain));}public void hashPutObject(String key, String hashKey, Object domain) {this.hashOperations.put(key, hashKey, domain);}public Boolean hashPutIfAbsent(String key, String hashKey, String value) {return this.hashOperations.putIfAbsent(key, hashKey, value);}public void hPutAll(String key, Map<String, String> maps) {this.hashOperations.putAll(key, maps);}public Map<String, Object> hashTable(String key) {return this.hashOperations.entries(key);}public Object hashGet(String key, Object hashKey) {return this.hashOperations.get(key, hashKey);}public String hashGetString(String key, String hashKey) {Object object = this.hashGet(key, hashKey);return object == null ? null : object.toString();}public List<String> hmGetString(String key, Collection<String> hashKeys) {List<Object> values = this.hashOperations.multiGet(key, hashKeys);return null != values ?(List) values.stream().filter(Objects::nonNull).map(String::valueOf).collect(Collectors.toList()) :Collections.emptyList();}public <T> T hashGetClass(String key, String hashKey, Class<T> clazz) {String value = this.hashGetString(key, hashKey);return value == null ? null : JsonUtils.fromJson(value, clazz);}public JSONObject hashGetJsonObject(String key, String hashKey) {String value = this.hashGetString(key, hashKey);return value == null ? null : JsonUtils.fromJson(value);}public Long hashDelete(String key, String... hashKey) {return this.hashOperations.delete(key, hashKey);}public long hashIncr(String key, String hashKey, long increment) {return this.hashOperations.increment(key, hashKey, increment);}public Double hashIncrByDouble(String key, String hashKey, double delta) {return this.hashOperations.increment(key, hashKey, delta);}public Long hashGetSize(String key) {return this.hashOperations.size(key);}public RedisTemplate<String, Object> getRedisTemplate() {return this.redisTemplate;}
}

思考:

1.上面代码有点多,既然是springBoot了,各种属性文件还需要配置吗,不是自动装配吗,但是没有找到属性文件

2.RedissonClinet需要自己初始化吗,应该需要的,但是看到其他项目并没有初始化动作,后续补充

Redisson + Lettuce实现相关推荐

  1. jedis使用_Redis的三个框架:Jedis,Redisson,Lettuce

    Jedis api 在线网址:http://tool.oschina.net/uploads/apidocs/redis/clients/jedis/Jedis.html redisson 官网地址: ...

  2. Redis的三个框架:Jedis,Redisson,Lettuce

    Jedis api 在线网址:http://tool.oschina.net/uploads/apidocs/redis/clients/jedis/Jedis.html redisson 官网地址: ...

  3. SpringBoot 操作 Redis的各种实现(以及Jedis、Redisson、Lettuce的区别比较)

    点击关注公众号,实用技术文章及时了解 来源:blog.csdn.net/qq_42105629/ article/details/102589319 一.Jedis,Redisson,Lettuce三 ...

  4. SpringBoot使用Redis 数据访问(单点、集群、哨兵、连接池、Pipline、分布式框架Redisson、解决方案)

    目录 Redis 文献资料 用Redis编程 Redis模块API 教程和常见问题解答 管理 嵌入式和物联网 故障排除 Redis集群 其他基于Redis的分布式系统 在SSD和永久性存储器上进行Re ...

  5. Spring Boot + Redis 操作多种实现

    欢迎关注方志朋的博客,回复"666"获面试宝典 一.Jedis,Redisson,Lettuce三者的区别 共同点:都提供了基于Redis操作的Java API,只是封装程度,具体 ...

  6. Spring Boot + Redis 实现各种操作,写得太好了吧!

    欢迎关注方志朋的博客,回复"666"获面试宝典 来源:blog.csdn.net/qq_42105629/article/details/102589319 一.Jedis,Red ...

  7. Spring Boot 操作 Redis 的各种实现

    欢迎关注方志朋的博客,回复"666"获面试宝典 一.Jedis,Redisson,Lettuce三者的区别 共同点:都提供了基于Redis操作的Java API,只是封装程度,具体 ...

  8. MySQL锁知识点复习,面试问到的概率超90%

    一.对MySQL的锁的了解 当数据库有并发事务的时候,可能会产生数据的不一致,这时候需要一些机制来保证访问的次序,锁机制就是这样的一个机制. 就像酒店的房间,如果大家随意进出,就会出现多人抢夺同一个房 ...

  9. 淘宝开源的代码质量检测工具,真强啊~

    来源:github.com/ice-lab/iceworks/tree/master/ 好的代码一定是整洁的,并且能够帮助阅读的人快速理解和定位.好的代码可以加快应用的开发迭代速度,不必花过多的时间来 ...

  10. 阿里云项目经理:Redis 开发规范

    一.键值设计 1. key名设计 (1)[建议]: 可读性和可管理性 以业务名(或数据库名)为前缀(防止key冲突),用冒号分隔,比如业务名:表名:id ugc:video:1 (2)[建议]:简洁性 ...

最新文章

  1. .net 提供不通过反射访问不同数据库吗?
  2. 详解CoordinatorLayout
  3. 第六十六期:软件架构之道的一次感悟
  4. TypeError: ‘NoneType‘ object is not callable--python报错解决办法
  5. 将Android手机打造成你的Python开发者桌面#华为云·寻找黑马程序员#
  6. STM8单片机串口发送引脚和接收引脚分开使用
  7. python实现多线程输出123123
  8. Spring的两种定时器
  9. JAVA 下载Word文档
  10. Promethus(普罗米修斯)监控系统
  11. 一文读懂Hoo Smart Chain的可视化公链
  12. 每日 30 秒 ⏱ 强风吹拂
  13. html5设置全屏背景图,HTML5 body设置全屏背景图片 如何让body的背景图片自适应整个屏----实战经验...
  14. c++11:std::declval、decltype
  15. 图片社交php,图像社交时代
  16. CentOS安装XenServer Tools
  17. 魏副业而战:闲鱼无货源爆款热销产品推荐
  18. Linux系统管理上机作业1
  19. 金立官宣M11系列即将到来,金粉是否能够重回怀抱,让我们拭目以待
  20. 12小时,教室与生产线接力 复旦MBA科创青干营首个整合实践活动日

热门文章

  1. bzoj 4501 旅行
  2. 戴尔DCS两周年庆 推新型数据中心设备
  3. 光伏行业缘何抢屋顶?
  4. C#实现10进制转2进制
  5. Zabbix安装记录
  6. 内存映射第一步:idmap swapper
  7. Hard lockup occurs due to an infinite loop encountered in distribute_cfs_runtime()
  8. vue的视图化创建项目_vuecli 创建项目的方法,以及图像化操作【23】
  9. Android 四大组件学习之Activity六
  10. Linux字符设备驱动实现