一、三种客户端比较

Jedis : 学习成本低,以 Redis 命令作为方法名称,但是其线程不安全

lettuce:基于 Netty 实现,支持同步、异步、响应式编程(SpringBoot),并且线程安全。支持 Redis 的哨兵模式、集群模式和管道模式。

Redisson: 基于 Redis 实现的分布式、可伸缩的 Java 数据结构集合。

二、Jedis 基础使用

  1. 引入依赖
        <dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>4.3.1</version></dependency>
  1. 使用单元测试进行测试
package com.example.redis;import lombok.Data;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.Jedis;@SpringBootTest
class RedisApplicationTests {private Jedis jedis;@BeforeEachvoid setUp(){jedis = new Jedis("192.168.33.10", 6379); // new 一个 jedis 对象jedis.select(0);}@Testvoid contextLoads() {jedis.set("testJedis", "存入成功");String haha = jedis.get("testJedis");System.out.printf(haha);}}

三、SpringDataRedis

1. SpringDataRedis 基础概况



2. 使用步骤

1)导入依赖

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
        <dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.11.1</version></dependency>

2)编写配置文件

spring:redis:host: 192.168.33.10 # 你的 redis 地址#数据库索引database: 0port: 6379#password:#连接超时时间(ms)timeout: 5000# 自定义redis默认过期时间(单位:时)expire-time: 24jedis:pool:# 连接池最大连接数(使用负值表示没有限制)max-active: -1# 连接池最大阻塞等待时间(使用负值表示没有限制)max-wait: -1

3) 测试连接

package com.example.redis;import lombok.Data;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.Jedis;@SpringBootTest
class RedisApplicationTests {@Autowired //自动注入即可private RedisTemplate redisTemplate;@Testvoid contextLoads() {redisTemplate.opsForValue().set("testRedisTemplate", "测试成功");redisTemplate.opsForValue().get("testRedisTemplate");}}

4) 对象类型序列化存储

———— 方式一:

redisTemplate 的 key 和 value 都是对象类型。key 和 value 会先被序列化,然后存储 ,若是自己不定义序列化方式,会用默认的 jdk 的序列化器 。这种方式序列化出来的 key 和 value 往往是读不友好的,因此我们要自定义序列化方式。

在具体实现时,我们将 key 固定为 String 类型 ( key 一般情况都是 String 类型),将 Value 固定为 Object 类型,key 使用 RedisSerializer.string() 方式序列化,value 使用 GenericJackson2JsonRedisSerializer 序列化器序列化。

  • 为容器中注入一配置类设置 RedisTemplate序列化方式:
package com.example.redis.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){// 创建 RedisTemplate 对象RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();// 设置连接工厂redisTemplate.setConnectionFactory(redisConnectionFactory);// 创建 JSON 序列化工具GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();// 设置 key 的序列化 (用 String 类型的序列化)redisTemplate.setKeySerializer(RedisSerializer.string());redisTemplate.setHashKeySerializer(RedisSerializer.string());// 设置 value 的序列化 (用 jack 类型的序列化)redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);redisTemplate.setHashKeySerializer(genericJackson2JsonRedisSerializer);return redisTemplate;}
}
  • 存储读取对象测试:
// City 对象
package com.example.redis.bean;import lombok.Data;import java.io.Serializable;@Data
public class City implements Serializable {private int id;private String name;private String countryCode;private String district;private String population;
}
// 测试类@Autowiredprivate RedisTemplate<String, Object> redisTemplate;@Testvoid contextLoads() {City city = new City();city.setId(1);city.setName("沈阳");city.setPopulation("10000");city.setDistrict("haha");city.setCountryCode("中国");redisTemplate.opsForValue().set("city:1", city);City c = (City) redisTemplate.opsForValue().get("city:1");System.out.printf("*********************************************" + c + "************************************");}

结果截图:

———— 方式二:

GenericJackson2JsonRedisSerializer 的问题

GenericJackson2JsonRedisSerializer 存储对象时夹带了私货 , @class 占用了额外内存空间,但是但是不加 @class 就不能自动反序列化,因此我们提出方式二。

解决 GenericJackson2JsonRedisSerializer 空间占用问题:

存储对象时对对象进行 手动序列化 和 反序列化,具体实现时,使用SpringMVC 提供的 ObjectMapper 类的 writeValueAsString 和 readValue 方法对对象进行序列化和反序列化。

示例代码如下:

import com.example.redis.bean.City;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;@SpringBootTest
class RedisStringApplicationTests {@Autowiredprivate StringRedisTemplate redisTemplate;// SpringMVC 中手动序列化的工具private static final ObjectMapper mapper = new ObjectMapper();@Testvoid contextLoads() throws JsonProcessingException {// 创建对象City city = new City();city.setId(1);city.setName("沈阳");city.setPopulation("10000");city.setDistrict("haha");city.setCountryCode("中国");// 手动序列化String json = mapper.writeValueAsString(city);// 写入数据redisTemplate.opsForValue().set("city:2", json);// 获取数据String getCityJson = redisTemplate.opsForValue().get("city:2");// 手动反序列化为对象City c = mapper.readValue(getCityJson, City.class);System.out.println("****************************" + c + "************************");}
}

结果截图

通过这种方式存储的对象数据就清清爽爽了

5) Hash 数据结构操作测试

@SpringBootTest
class RedisHashApplicationTests {@Autowiredprivate StringRedisTemplate stringRedisTemplate;@Testvoid contextLoads() {// 存数据stringRedisTemplate.opsForHash().put("city:3", "id", "3");stringRedisTemplate.opsForHash().put("city:3", "name", "北京");// 取数据Map<Object, Object> entries =  stringRedisTemplate.opsForHash().entries("city:3");System.out.printf("*********************************************" + entries);}
}

【Redis】使用 Java 客户端连接 Redis相关推荐

  1. redis php 性能测试工具,redis性能测试与客户端连接详解

    Redis 性能测试(推荐:redis入门教程) 语法redis-benchmark [option] [option value] 实例 实例一 以下实例同时执行 1000 个请求来检测性能:$ r ...

  2. Redis介绍 Java客户端操作Redis

    Redis介绍 && Java客户端操作Redis 本文内容 redis介绍 redis的 shell 客户端简介 redis的 java 客户端简介 环境配置 redis 2.8.1 ...

  3. Redis介绍 Java客户端操作Redis

    分享一下我老师大神的人工智能教程.零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow Redis介绍 & ...

  4. 虚拟机安装fastdfs之后,java客户端连接超时问题,查看开放端口

    虚拟机安装fastdfs之后,java客户端连接超时问题 java.net.SocketTimeoutException: connect timed out 报错信息显示是连接超时,因为fastdf ...

  5. 03-Redis客户端连接Redis服务器(redis.conf 文件配置没有生效导致redis运行报错Error: Connection reset by peer)

    参考此链接配置 redis.conf,然后本文章才能继续操作 EditPlus连接Centos7修改Redis配置文件(建议FinalShell修改更加方便)https://blog.csdn.net ...

  6. 005,使用Java客户端连接RabbitMQ,构造我们的第一个Publish和Consumer应用

    2019独角兽企业重金招聘Python工程师标准>>> 官网地址:http://www.rabbitmq.com/documentation.html    如下图: 在客户端连接服 ...

  7. Linux使用Redis客户端连接Redis

    1).进入redis的安装目录 [root@localhost ~]# cd /usr/local/redis/bin/ [root@localhost bin]# 2).使用客户端进行连接redis ...

  8. hadoop fs命令无法使用_Hadoop从入门到入土(三)HDFS集群简单维护及JAVA客户端连接HDFS...

    集群简单维护 查看日志 上篇我们搭建了集群,并且完成了hdfs的搭建,但在我的linux02和linux03上,发现一个问题,我启动了datanode之后,开始进程还在,一会就自己消失了,这是为什么呢 ...

  9. EMQX(五)—JAVA客户端连接操作EMQX服务

    前言 EMQX提供了很多客户端SDK,如java,js,C++等.除此之外,只要满足MQTT协议的客户端,都可以对EMQX主题进行连接.下面我们讲解java的SDK客户端. 一.Eclipse Pah ...

最新文章

  1. 没有绝对安全的系统!激光瞄准二极管,25米外从被物理隔绝的计算机中窃取数据...
  2. mysql事物 总结_Mysql事务总结
  3. mysql数据库 day06
  4. 诗与远方:无题(七十八)- 望天而作
  5. AOP 详解 、AOP 中通知类型 、AOP 两种实现方式(Schema-base 和 AspectJ)
  6. Hadoop配置项整理(hdfs-site.xml)
  7. Leetcode每日一题:143.reorder-list(重排列表)
  8. Dataset增加行数据及常用方法
  9. c#读取文本文件出现乱码
  10. 计算机信息检索自考知识点,计算机信息检索02139自考资料.docx
  11. java一些基础知识点
  12. 华为全球发布UMTS终端商用新品
  13. mysql同时满足升序和降序_mysql升序和降序语句
  14. hive函数中的operators, UDF, UDAF, UDTF, PTF
  15. 任泉自曝在Star VC年薪100万 今年重点投资互联网金融
  16. android手机解锁成功后的广播,Android动态注册锁屏、解锁、开屏系统广播
  17. 第九周项目——穷举法之三色球
  18. 五轴数控转台_什么是五轴联动数控机床
  19. 用 Python 去除 PDF 水印,你学会吗?
  20. Android 使用fastboot命令刷机流程

热门文章

  1. 这些开发好工具,你知道几个?
  2. MainThread 和 RenderThread 解读
  3. 单内存16g和双8g差别大吗_内存挑选方面也有玄学?单16G和双8G有啥区别?
  4. Go C 编程 第9课 放飞汽球(魔法学院的奇幻之旅 Go C编程绘图)
  5. IDEA 的空的包名默认被折叠,已解决
  6. 艾媒直播行业报告出炉 花椒直播何以扩大领先优势?
  7. Java导出Excel表合并行、合并列
  8. 前端vue和django后端数据交互,跨域问题的解决
  9. 关于 win10 bat 定时任务设定 schtasks 若干个问题
  10. 面试必问:Spring循环依赖