栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

redis高级: redisTemplate 修改默认的jdk序列化方式/StringRedisTemplate

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

redis高级: redisTemplate 修改默认的jdk序列化方式/StringRedisTemplate

目录

场景: 使用springboot自带的redistemplate 连接redis

效果: xacxedx00x05tx00x07auther1

方式一:(源码中可以看到 粘贴到需要的方法内)

方式二:  写一个配置类(简单)

 =============> 方法三(高级) <==============

1. 导入依赖: 

2. 写自定义序列化类

3. redis的高级序列化配置

4. 再次测试: (测试代码)


场景: 使用springboot自带的redistemplate 连接redis

两种 StringRedisTemplate redisTemplate

而 redisTemplate 存储的 是默认的jdk序列化方式

效果: xacxedx00x05tx00x07auther1
@Test
    void testString() {
        ValueOperations value = redisTemplate.opsForValue();
        value.set("name","pzy");
        value.set("auther","pzyzx",10); //向右偏移10个字符
        value.set("auther1","pzyzx", Duration.ofSeconds(10)); //10秒后过期
        String name = value.get("name");//xacxedx00x05tx00x07auther1
        System.out.println(name);
    }

修改 默认的序列化方式

方式一:(源码中可以看到 粘贴到需要的方法内)
        //修改序列化方式(自定义) 源码中有
       redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setValueSerializer(RedisSerializer.string());
       redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setHashValueSerializer(RedisSerializer.string());

方式二:  写一个配置类(简单)

序列化方式相同

@Configuration
public class RedisConfig {//RedisAutoConfiguration

    //简单定制
    @Bean
    public RedisTemplate redisTemplate(
           RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        //设置key的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());
        //设置值的序列化方式
        template.setValueSerializer(RedisSerializer.json());
        template.setHashValueSerializer(RedisSerializer.json());
        return template;
    }
}

效果(统一)

 =============> 方法三(高级) <==============

1. 导入依赖: 

            com.alibaba.fastjson2
            fastjson2
            2.0.3
        

2. 写自定义序列化类
Redis使用FastJson序列化
package cn.pingzhuyan.config;

import java.nio.charset.Charset;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

public class FastJson2JsonRedisSerializer implements RedisSerializer {
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class clazz;


    public FastJson2JsonRedisSerializer(Class clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
    }
}

3. redis的高级序列化配置
package cn.pingzhuyan.config;



import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
//@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
//    @SuppressWarnings(value = {"unchecked", "rawtypes"})
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}

4. 再次测试: (测试代码)
package cn.pingzhuyan.config;



import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
//@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
//    @SuppressWarnings(value = {"unchecked", "rawtypes"})
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/944154.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号