背景:
最近项目采用前后端分离的架构,单点登录系统采用Redis存储用户session信息,在这里总结下springboot整合redis的详细过程,以及部分源码分析


1、前期准备

首先保证安装好redis,并开启远程访问权限(最好配置密码)

pom.xml:

添加依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml:

spring:redis:database: 0host: 140.143.23.94password: 123port: 6379timeout: 3000       # 连接超时时间 单位 ms(毫秒)
#    cluster:
#      nodes: 10.3.1.4:7000,10.3.1.4:7001,...,10.3.1.4:7008pool:max-idle: 8       # 连接池中的最大空闲连接,默认值也是8min-idle: 0       # 连接池中的最小空闲连接,默认值也是0max-active: 8     # 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。max-wait: -1      # 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出

选择合适的API:

这个主要是根据redis存储的数据类型需求决定,key一般都是String,但是value可能不一样,一般有两种,String和 Object
如果k-v都是String类型,我们可以直接用 StringRedisTemplate,这个是官方建议的,也是最方便的,直接导入即用,无需多余配置!
如果k-v是Object类型,则需要自定义 RedisTemplate,在这里我们都研究下!


2、StringRedisTemplate

redis封装工具类:(内部导入的是StringRedisTemplate,RedisTemplate也可以)

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;import java.util.concurrent.TimeUnit;/*** @Author: yuanj* @Date: 2018/5/31 13:53*/
@Service
@Slf4j
public class IRedisService {@Autowiredprotected StringRedisTemplate redisTemplate;/*** 写入redis缓存(不设置expire存活时间)* @param key* @param value* @return*/public boolean set(final String key, String value){boolean result = false;try {ValueOperations operations = redisTemplate.opsForValue();operations.set(key, value);result = true;} catch (Exception e) {log.error("写入redis缓存失败!错误信息为:" + e.getMessage());}return result;}/*** 写入redis缓存(设置expire存活时间)* @param key* @param value* @param expire* @return*/public boolean set(final String key, String value, Long expire){boolean result = false;try {ValueOperations operations = redisTemplate.opsForValue();operations.set(key, value);redisTemplate.expire(key, expire, TimeUnit.SECONDS);result = true;} catch (Exception e) {log.error("写入redis缓存(设置expire存活时间)失败!错误信息为:" + e.getMessage());}return result;}/*** 读取redis缓存* @param key* @return*/public Object get(final String key){Object result = null;try {ValueOperations operations = redisTemplate.opsForValue();result = operations.get(key);} catch (Exception e) {log.error("读取redis缓存失败!错误信息为:" + e.getMessage());}return result;}/*** 判断redis缓存中是否有对应的key* @param key* @return*/public boolean exists(final String key){boolean result = false;try {result = redisTemplate.hasKey(key);} catch (Exception e) {log.error("判断redis缓存中是否有对应的key失败!错误信息为:" + e.getMessage());}return result;}/*** redis根据key删除对应的value* @param key* @return*/public boolean remove(final String key){boolean result = false;try {if(exists(key)){redisTemplate.delete(key);}result = true;} catch (Exception e) {log.error("redis根据key删除对应的value失败!错误信息为:" + e.getMessage());}return result;}/*** redis根据keys批量删除对应的value* @param keys* @return*/public void remove(final String... keys){for(String key : keys){remove(key);}}
}

使用:(Autowired导入即可使用)

@Autowired
IRedisService iRedisService;//将session信息存入redis,设置存活时间为30分钟
iRedisService.set(sessionid, sessionJson, 30*60L);

3、RedisTemplate

我们在此存入redis的类型为:String:Object

RedisTemplate中定义了对5种数据结构操作:redisTemplate.opsForValue();//操作字符串
redisTemplate.opsForHash();//操作hash
redisTemplate.opsForList();//操作list
redisTemplate.opsForSet();//操作set
redisTemplate.opsForZSet();//操作有序set

自定义Redis序列化工具类:

/*** @Author: yuanj* @CreateDate: 2018/6/3 14:24* @Version: 1.0*/
public class RedisObjectSerializer implements RedisSerializer<Object> {static final byte[] EMPTY_ARRAY = new byte[0];@Overridepublic Object deserialize(byte[] bytes) {if (isEmpty(bytes)) {return null;}ObjectInputStream oii = null;ByteArrayInputStream bis = null;bis = new ByteArrayInputStream(bytes);try {oii = new ObjectInputStream(bis);Object obj = oii.readObject();return obj;} catch (Exception e) {e.printStackTrace();}return null;}@Overridepublic byte[] serialize(Object object) {if (object == null) {return EMPTY_ARRAY;}ObjectOutputStream obi = null;ByteArrayOutputStream bai = null;try {bai = new ByteArrayOutputStream();obi = new ObjectOutputStream(bai);obi.writeObject(object);byte[] byt = bai.toByteArray();return byt;} catch (IOException e) {e.printStackTrace();}return null;}private boolean isEmpty(byte[] data) {return (data == null || data.length == 0);}}

Redis配置类:

我看网上大多数都是配置Jackson2JsonRedisSerializer序列化类,我这测试发现不是很好用,所以用自己自定义的序列化类!

/*** @Author: yuanj* @CreateDate: 2018/6/3 14:00* @Version: 1.0*/
@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();RedisObjectSerializer redisObjectSerializer = new RedisObjectSerializer();RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();template.setConnectionFactory(redisConnectionFactory);template.setKeySerializer(stringRedisSerializer);template.setValueSerializer(redisObjectSerializer);return template;}
}

定义测试User实体类:

public class User implements Serializable{private static final long serialVersionUID = -8289770787953160443L;public User(Integer userId, String userName, String password, String phone) {this.userId = userId;this.userName = userName;this.password = password;this.phone = phone;}private Integer userId;private String userName;private String password;private String phone;public Integer getUserId() {return userId;}public void setUserId(Integer userId) {this.userId = userId;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}@Overridepublic String toString() {return "User{" +"userId=" + userId +", userName='" + userName + '\'' +", password='" + password + '\'' +", phone='" + phone + '\'' +'}';}
}

使用测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class YjApplicationTests {@Autowiredprivate IRedisService iRedisService;@Autowiredprivate RedisTemplate<String, Object> redisTemplate;@Testpublic void testRedis(){
//      iRedisService.set("aaa","BBB");redisTemplate.opsForValue().set("user1",new User(1,"yj","123","111"));User user1 = (User)redisTemplate.opsForValue().get("user1");System.out.println(user1);}
}



4、StringRedisTemplate 和 RedisTemplate 对比分析

总结了一下区别和联系主要有四点:

第一点,StringRedisTemplate继承了RedisTemplate。

第二点,RedisTemplate是一个泛型类,而StringRedisTemplate则不是。

第三点,StringRedisTemplate只能对key=String,value=String的键值对进行操作,RedisTemplate可以对任何类型的key-value键值对操作。

第四点,是他们各自序列化的方式不同,但最终都是得到了一个字节数组,殊途同归,StringRedisTemplate使用的是StringRedisSerializer类;RedisTemplate使用的是JdkSerializationRedisSerializer类。反序列化,则是一个得到String,一个得到Object

源码分析:

先看 StringRedisTemplate:

StringRedisTemplate 是继承 RedisTemplate的,一般来说子类继承父类,应该能实现更多的功能,但是此处我们发现 StringRedisTemplate 继承的是 RedisTemplate的泛型类,指定了String-String的泛型!故功能只专注于String类型!


其次我们可以看到 StringRedisTemplate 的构造方法中指定了序列化类为 StringRedisSerializer,我们进去看看:

这下就一目了然了!

再看 RedisTemplate:

可以看到默认序列化方式为 JdkSerializationRedisSerializer

而JdkSerializationRedisSerializer又调用了SerializingConverter类的convert方法。在这个方法里其转换主要有三步:

1、ByteArrayOutputStream(1024),创建一个字节数组输出流缓冲区。

2、DefaultSerializer.serialize(source, byteStream):把要序列化的数据存储到缓冲区。还想看他是怎么放到缓冲区的,但是,能力有限,水平一般,serialize的细节,实在无能为力,看了半天,还是氐惆。

3、toByteArray:就是把上一步放到缓冲区的数据拷贝到新建的字节数组里。

至此Object的序列化就结束了,返回了一个字节数组。

SpringBoot 整合 Redis 使用详解(StringRedisTemplate 和 RedisTemplate 对比分析)相关推荐

  1. Springboot整合redis配置详解

    Springboot整合redis配置详解 1.导入依赖 <dependency><groupId>org.springframework.boot</groupId&g ...

  2. Springboot 整合 Dubbo/ZooKeeper 详解 SOA 案例

    摘要: 原创出处:www.bysocket.com 泥瓦匠BYSocket 希望转载,保留摘要,谢谢! "看看星空,会觉得自己很渺小,可能我们在宇宙中从来就是一个偶然.所以,无论什么事情,仔 ...

  3. SpringBoot集成Redis代码详解,收藏起来

    今天主要讲解Springboot整合Redis.Redis是目前使用最多的缓存,包括Spring Boot 中我们也是会用Redis做很多事情.那么今天就来说一说Spring Boot如何整合Redi ...

  4. springboot整合mysql5.7_详解SpringBoot整合MyBatis详细教程

    1. 导入依赖 首先新建一个springboot项目,勾选组件时勾选Spring Web.JDBC API.MySQL Driver 然后导入以下整合依赖 org.mybatis.spring.boo ...

  5. springboot整合log4j全过程详解

    1.在pom.xml中导入log4j依赖,注意在导入依赖之前要先关闭Spring中默认的日志 以此来关闭默认日志: <dependency><groupId>org.sprin ...

  6. springboot2.5.0 整合 redis 配置详解

    1. pom添加依赖 <!--redis--><dependency><groupId>org.springframework.boot</groupId&g ...

  7. 【七】springboot整合redis(超详细)

    springboot篇章整体栏目: [一]springboot整合swagger(超详细 [二]springboot整合swagger(自定义)(超详细) [三]springboot整合token(超 ...

  8. springboot整合redis,推荐整合和使用案例(2021版)

    背景:手下新人在初次使用springboot整合redis,大部分人习惯从网上检索到一份配置,然后不知其所以然的复制粘贴到项目中,网上搜索到的配置良莠不齐但又万变不离其宗.由于springboot最大 ...

  9. SpringBoot整合redis详解

    在SpringBoot中我们一般使用RedisTemplate提供的方法来操作Redis.那么使用SpringBoot整合Redis需要那些步骤呢? 1.JedisPoolConfig(这个是配置连接 ...

最新文章

  1. Python3 MySQL 数据库连接 - PyMySQL 驱动
  2. TensorFlow、Numpy中的axis的理解
  3. 20-javamail
  4. HDU - 3613 Best Reward(字符串哈希)
  5. 沃罗诺伊图是怎样的?
  6. 王晓初:没有收到消息和电信合并 希望合作步伐加快
  7. 【转】Ubuntu 16.04安装配置TensorFlow GPU版本
  8. 用python实现2048小游戏
  9. 【研发设计】多人开发模式下的Git工作流介绍
  10. 【海康威视】WPF客户端二次开发:【2】语音对讲
  11. spss 描述性分析
  12. 【SLAM】——编译项目orb-slam2_with_semantic_labelling
  13. ODOO 开源 ERP 和 CRM
  14. HTML5期末大作业:山河旅行社网站设计——山河旅行社网站(5页) HTML+CSS+JavaScript 学生DW网页 出行 旅途 游玩
  15. mate9 android os,华为Mate9评测:全新EMUI 5系统 永不卡顿的安卓机?
  16. ESP32开发--使用NVS存储数据
  17. 使用Python编写面向安卓模拟器的明日方舟挂机脚本
  18. 怎么录制视频声音,什么录音软件好用
  19. kafka一些常用命令,以及如何查看消息被谁消费了
  20. R语言 自定义函数之趣味程序--老虎机

热门文章

  1. 【echart】饼图 legend tooltip格式化比例为0不显示
  2. Deno加入ECMA
  3. 这样执着,究竟为什么?
  4. JavaScript , jQuery
  5. build iPhone toolchain for 3.0 in windows via CYGWIN
  6. springboot2整合Quartz持久化定时任务管理界面
  7. [乐意黎原创] 移动硬盘IO /IO 错误
  8. buuoj Pwn writeup 206-210
  9. 图片理解数字签名和验签过程
  10. 普华服务器操作系统v4.0,普化操作系统4.0特性_服务器准系统_服务器开发应用-中关村在线...