温馨提示×

redis如何实现序列化

小新
351
2020-12-13 15:20:35
栏目: 云计算

redis如何实现序列化

redis实现序列化的示例:

Redis提供了两个模板类RedisTemplate和StringRedisTemplate实现序列化,如:

1.RedisAutoConfiguration源码,对key和value进行序列化:

public class RedisAutoConfiguration {

public RedisAutoConfiguration() {

}

@Bean

@ConditionalOnMissingBean(

name = {"redisTemplate"}

)

//RedisTemplate的key和value都是Object类型的,如果进行网络传输或将数据存储到硬盘上就需对key和value进行序列化

public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {

RedisTemplate template = new RedisTemplate();

template.setConnectionFactory(redisConnectionFactory);

return template;

}

@Bean

@ConditionalOnMissingBean

public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {

StringRedisTemplate template = new StringRedisTemplate();

template.setConnectionFactory(redisConnectionFactory);

return template;

}

}

2.StringRedisTemplate源码,将key和value都序列化为String类型的:

//StringRedisTemplate类继承RedisTemplate

public class StringRedisTemplate extends RedisTemplate {

//将key和value都序列化为String类型的,也是只支持String类型的key和value

public StringRedisTemplate() {

this.setKeySerializer(RedisSerializer.string());

this.setValueSerializer(RedisSerializer.string());

this.setHashKeySerializer(RedisSerializer.string());

this.setHashValueSerializer(RedisSerializer.string());

}

}

0