配置redis的序列化,注入RedisTemplate方式
更新時間:2023年12月20日 09:34:16 作者:小晨想好好學(xué)習(xí)
這篇文章主要介紹了配置redis的序列化,注入RedisTemplate方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
配置redis的序列化,注入RedisTemplate
public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setConnectionFactory(factory); //key序列化方式 template.setKeySerializer(redisSerializer); //value序列化 template.setValueSerializer(jackson2JsonRedisSerializer); //value hashmap序列化 template.setHashValueSerializer(jackson2JsonRedisSerializer); return template; }
使用redis,必須配置redis序列化類
package com.example.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { // key 采用StringRedisSerializer // value 采用GenericJackson2JsonRedisSerializer RedisTemplate<String, Object> template = new RedisTemplate<>(); // 關(guān)閉啟用默認(rèn)配置 template.setEnableDefaultSerializer(false); // 連接工廠 template.setConnectionFactory(factory); // key 序列化方式 template.setKeySerializer(RedisSerializer.string()); // value 序列化方式 template.setValueSerializer(RedisSerializer.json()); // hash key 序列化方式 template.setHashKeySerializer(RedisSerializer.string()); // hash value 序列化方式 template.setHashValueSerializer(RedisSerializer.json()); // 配置完成 template.afterPropertiesSet(); return template; } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.4.0</version> </dependency>
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
redis的list數(shù)據(jù)類型相關(guān)命令介紹及使用
本文主要介紹了redis的list數(shù)據(jù)類型相關(guān)命令介紹及使用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01Spring boot+redis實(shí)現(xiàn)消息發(fā)布與訂閱的代碼
這篇文章主要介紹了Spring boot+redis實(shí)現(xiàn)消息發(fā)布與訂閱,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值需要的朋友可以參考下2020-04-04Redis實(shí)現(xiàn)UV統(tǒng)計(jì)的示例代碼
本文主要介紹了Redis實(shí)現(xiàn)UV統(tǒng)計(jì)的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01