Java--Redis-08-redis在SpringBoot中配置

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: 在Spring Boot中,我们可以通过配置来自定义一个属于我们自己的RedisTemplate。

在Spring Boot中,我们可以通过配置来自定义一个属于我们自己的RedisTemplate。

       在 SpringBoot2.x 之后,原来使用的jedis 被替换为了 lettuce,Jedis和Lettuce都是Redis Client,他两的区别是:

jedis : 采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用 jedis pool 连接 池!更像 BIO 模式

lettuce : 采用netty,实例可以在多个线程中进行共享,不存在线程不安全的情况!可以减少线程数据 了,更像 NIO 模式

序列化:

spring-data-redis中序列化类有以下几个:

GenericToStringSerializer:可以将任何对象泛化为字符串并序列化

Jackson2JsonRedisSerializer:序列化Object对象为json字符串。与JacksonJsonRedisSerializer相同

JdkSerializationRedisSerializer:序列化java对象

StringRedisSerializer:简单的字符串序列化


packagecom.xing.study.config;
importcom.fasterxml.jackson.annotation.JsonAutoDetect;
importcom.fasterxml.jackson.annotation.JsonTypeInfo;
importcom.fasterxml.jackson.annotation.PropertyAccessor;
importcom.fasterxml.jackson.databind.ObjectMapper;
importcom.fasterxml.jackson.databind.SerializationFeature;
importcom.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
importcom.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
importorg.springframework.context.annotation.Bean;
importorg.springframework.data.redis.connection.RedisConnectionFactory;
importorg.springframework.data.redis.core.RedisTemplate;
importorg.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
importorg.springframework.data.redis.serializer.StringRedisSerializer;
importjava.net.UnknownHostException;
@ComponentpublicclassRedisConfig {
@BeanpublicRedisTemplate<String,Object>redisTemplate(RedisConnectionFactoryredisConnectionFactory) throwsUnknownHostException {
RedisTemplate<String, Object>template=newRedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
// Json序列化配置Jackson2JsonRedisSerializer<Object>jackson2JsonRedisSerializer=newJackson2JsonRedisSerializer<>(Object.class);
ObjectMapperobjectMapper=newObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 解决jackson2无法反序列化LocalDateTime的问题objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.registerModule(newJavaTimeModule());
// 该方法过时// om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);// 上面 enableDefaultTyping 方法过时,使用 activateDefaultTypingobjectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// String 的序列化StringRedisSerializerstringRedisSerializer=newStringRedisSerializer();
// key采用String的序列化方式template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jacksontemplate.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jacksontemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
// 设置值(value)的序列化采用FastJsonRedisSerializer。// 设置键(key)的序列化采用StringRedisSerializer。template.afterPropertiesSet();
template.afterPropertiesSet();
returntemplate;
    }
}


如果使用lettuce,只要把注入参数改成 LettuceConnectionFactory 即可。

@BeanpublicRedisTemplate<String, Serializable>redisCacheTemplate(LettuceConnectionFactoryredisConnectionFactory) {
RedisTemplate<String, Serializable>template=newRedisTemplate<>();
template.setKeySerializer(newStringRedisSerializer());
template.setValueSerializer(newGenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
returntemplate;
    }


在官网文档上可以找到应用的配置属性:

spring.application.name=studyserver.port=8889#服务器主机。默认localhostspring.redis.host=${REDIS-HOST:127.0.0.1}
#Redis服务器端口。默认6379spring.redis.port=${REDIS-PORT:6379}
#redis服务器的登录用户名。#spring.redis.username=#redis服务器的登录密码。spring.redis.password=${REDIS-PASW:Y4WyYKR5}
#连接工厂使用的数据库索引。默认0spring.redis.database=${REDIS-DB:1}
#连接池在给定时间可以分配的最大连接数(使用负值表示没有限制)默认8spring.redis.jedis.pool.max-active=8#连接池中空闲连接的最大数量。使用负值表示无限数量的空闲连接。默认8spring.redis.jedis.pool.max-idle=8#连接池中的最小空闲连接数。此设置仅在驱逐运行之间的时间和时间均为正时才有效。默认0spring.redis.jedis.pool.min-idle=0#连接池耗尽时,在抛出异常之前连接分配的最大阻塞等待时间。使用负值无限期阻止。默认-1msspring.redis.jedis.pool.max-wait=3000#连接超时时间(毫秒)spring.redis.timeout=30000##连接超时。##spring.redis.connect-timeout=##要在与CLIENTSENATE的连接上设置的客户端名称。#spring.redis.client-name=##要使用的客户端类型。默认情况下,根据类路径自动检测。##spring.redis.client-type=###跨集群执行命令时要遵循的最大重定向数。#spring.redis.cluster.max-redirects=##用于与哨兵进行身份验证的密码。#spring.redis.sentinel.password=##以逗号分隔的“host:port”对列表,用于引导。这表示集群节点的“初始”列表,并且需要至少有一个条目。#spring.redis.cluster.nodes=##空闲对象驱逐线程运行之间的时间。当为正时,空闲对象驱逐线程启动,否则不执行空闲对象驱逐。#spring.redis.jedis.pool.time-between-eviction-runs=##是否应使用使用所有可用刷新触发器的自适应拓扑刷新。默认false#spring.redis.lettuce.cluster.refresh.adaptive=##是否发现并查询所有集群节点以获取集群拓扑。当设置为false时,只有初始种子节点用作拓扑发现的源。默认true##spring.redis.lettuce.cluster.refresh.dynamic-refresh-sources=true##集群拓扑刷新周期。#spring.redis.lettuce.cluster.refresh.period=##池在给定时间可以分配的最大连接数。使用负值表示没有限制。默认8#spring.redis.lettuce.pool.max-active=8##池中“空闲”连接的最大数量。使用负值表示无限数量的空闲连接。默认8#spring.redis.lettuce.pool.max-idle=8##当池耗尽时,在抛出异常之前连接分配应该阻塞的最长时间。使用负值无限期阻止。默认-1ms#spring.redis.lettuce.pool.max-wait=-1ms##池中要维护的最小空闲连接数的目标。此设置仅在驱逐运行之间的时间和时间均为正时才有效。默认0#spring.redis.lettuce.pool.min-idle=0##空闲对象驱逐线程运行之间的时间。当为正时,空闲对象驱逐线程启动,否则不执行空闲对象驱逐。#spring.redis.lettuce.pool.time-between-eviction-runs=##关机超时。默认100ms#spring.redis.lettuce.shutdown-timeout=100ms##Redis服务器的名称。#spring.redis.sentinel.master=##逗号分隔的“主机:端口”对列表。#spring.redis.sentinel.nodes=##是否启用SSL支持。默认#spring.redis.ssl=false##连接网址。覆盖主机、端口和密码。用户被忽略。示例:redis://user: password@example.com :6379#spring.redis.url=

image.png


总结:

       每个公司或者个人都会自己搞一个RedisTemplate和封装一个RedisUtil。每个版本都会有API被弃用,有啥就上官方文档查吧。

       奥里给!!!



END

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
打赏
0
1
0
0
226
分享
相关文章
|
30天前
基于springboot+thymeleaf+Redis仿知乎网站问答项目源码
基于springboot+thymeleaf+Redis仿知乎网站问答项目源码
131 36
java springboot监听事件和处理事件
通过上述步骤,开发者可以在Spring Boot项目中轻松实现事件的发布和监听。事件机制不仅解耦了业务逻辑,还提高了系统的可维护性和扩展性。掌握这一技术,可以显著提升开发效率和代码质量。
92 33
SpringBoot自动配置及自定义Starter
Java程序员依赖Spring框架简化开发,但复杂的配置文件增加了负担。SpringBoot以“约定大于配置”理念简化了这一过程,通过引入各种Starter并加载默认配置,几乎做到开箱即用。
116 10
SpringBoot自动配置及自定义Starter
如何配置 Java 环境变量:设置 JAVA_HOME 和 PATH
本文详细介绍如何在Windows和Linux/macOS系统上配置Java环境变量。
818 12
基于Java+SpringBoot+Vue实现的车辆充电桩系统设计与实现(系统源码+文档+部署讲解等)
面向大学生毕业选题、开题、任务书、程序设计开发、论文辅导提供一站式服务。主要服务:程序设计开发、代码修改、成品部署、支持定制、论文辅导,助力毕设!
55 6
NoSQL与Redis配置与优化
通过合理配置和优化Redis,可以显著提高其性能和可靠性。选择合适的数据结构、优化内存使用、合理设置持久化策略、使用Pipeline批量执行命令、以及采用分布式集群方案,都是提升Redis性能的重要手段。同时,定期监控和维护Redis实例,及时调整配置,能够确保系统的稳定运行。希望本文对您在Redis的配置与优化方面有所帮助。
70 23
【潜意识Java】javaee中的SpringBoot在Java 开发中的应用与详细分析
本文介绍了 Spring Boot 的核心概念和使用场景,并通过一个实战项目演示了如何构建一个简单的 RESTful API。
38 5
|
1月前
|
CentOS7.8配置Adoptium-Java17运行环境
本指南介绍如何设置清华镜像源并安装 Temurin-17-JRE 运行环境。首先,编辑 `/etc/yum.repos.d/adoptium.repo` 文件,配置清华镜像源。接着,使用 `yum install -y temurin-17-jre` 命令安装 Temurin-17-JRE,并通过 `java --version` 验证安装成功。相关配置和操作界面截图附后。
45 8
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
52 2
java springboot监听事件和处理事件
通过上述步骤,开发者可以在Spring Boot项目中轻松实现事件的发布和监听。事件机制不仅解耦了业务逻辑,还提高了系统的可维护性和扩展性。掌握这一技术,可以显著提升开发效率和代码质量。
75 13