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
发布评论