springboot配置redis

编程入门 行业动态 更新时间:2024-10-28 19:25:01

<a href=https://www.elefans.com/category/jswz/34/1769943.html style=springboot配置redis"/>

springboot配置redis

1.Jedis库

依赖库

<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>5.0.2</version>
</dependency>

使用案例:

 @Testpublic void jedis(){Jedis jedis = new Jedis("127.0.0.1", 6379);jedis.set("name","yi");jedis.close();}

2.springboot官方编写的整合库

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

使用案例:

 	@Autowiredprivate RedisTemplate redisTemplate;//通过自动注入@Testpublic void t(){//使用opsFor系列方法获取xxxOperations对象ValueOperations valueOperations = redisTemplate.opsForValue();valueOperations.set("xxx","yi");}

RedisTemplate默认使用 JdkSerializationRedisSerializer 进行序列化。
序列化的key结果为:

为什么是这样一串奇怪的 16 进制? ObjectOutputStream#writeString(String str, boolean unshared) 实际就是标志位 + 字符串长度 + 字符串内容

如果需要redis中设定的key值与我们在程序中设定的值相同,则需要改变序列化的方式,即自定义RedisTemplate。
创建一个配置类来定义RedisTemplate Bean,设置序列化方式 StringRedisSerializer。

@Configuration
public class RedisConfiguration extends CachingConfigurerSupport {@BeanRedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){RedisTemplate<Object,Object> redisTemplate = new RedisTemplate();redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(new StringRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setConnectionFactory(redisConnectionFactory);return redisTemplate;}
}

更多推荐

springboot配置redis

本文发布于:2023-12-03 13:33:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1655902.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:springboot   redis

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!