springboot整合redis实例分析
作者:CalmWind
时间:2023-04-26
来源:互联网
浏览:0
导入redispom文件org.springframework.bootspring-boot-starter-data-redis编写redis配置spring:redis:password:port:6379host:localhostdatabase:0jedis:pool:##连接池最大连接数(使用负值表示没有限制)#spring.redis.pool.max-active=8max-active:8##连接池最大阻塞等待时间(使用负值表示没有限制)#spring.redis.pool.max-w
导入redis pom文件
org.springframework.boot spring-boot-starter-data- redis
编写redis配置
spring: redis: password: port: 6379 host: localhost database: 0 jedis: pool: ## 连接池最大连接数(使用负值表示没有限制) #spring.redis.pool.max-active=8 max-active: 8 ## 连接池最大阻塞等待时间(使用负值表示没有限制) #spring.redis.pool.max-wait=-1 max-wait: -1 ## 连接池中的最大空闲连接 #spring.redis.pool.max-idle=8 max-idle: 8 ## 连接池中的最小空闲连接 #spring.redis.pool.min-idle=0 min-idle: 0 ## 连接超时时间(毫秒) lettuce: shutdown-timeout: 0
编写springConfig文件
由于存储需要序列化,所以我们要配置redis的序列化方式,如果不配置的话key和value默认使用的都是StringRedisSerializer,只能用来存储String类型的数据,因此需要配置我们常用的类型。同时我们的Java实体类也要一定要继承Serializable接口
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory){
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
} 测试redis
在这一步前,我们要确定所连接的redis服务已经开启
@Autowired private RedisTemplateredisTemplate; @Test public void testSelect() throws SQLException { redisTemplate.opsForValue().set("qqq",userMapper.findByUname("zengkaitian")); System.out.println("redis中获取的:"+redisTemplate.opsForValue().get("qqq")); }
测试结果
作者最新文章
PDF转图片在线怎么用?资料整理的简单流程
2026-09-03 12:12
科大讯飞发布星火多模态大模型X2-VL,基于全国产算力训练
2026-08-25 16:21
雷军小米YU7装600斤车厘子慰问工程师被指违规 回应:封闭道路分装 交警称后排满载不合法
2026-08-25 15:23
Anthropic禁用Fable 5模型,亚马逊CEO贾西或是背后导火索
2026-08-25 14:58
长虹T06(双4G)忘了手机密码怎么办?
2026-08-25 13:40
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















