SpringBoot 使用 RedisTemplate 時,存入 Key 和 Value 出現(xiàn)亂碼: \xAC\xED\x00\x05t\x00...

原因: RedisTemplate 默認使用:JdkSerializationRedisSerializer 序列化。

解決方案:

@Autowired
RedisTemplate redisTemplate;

修改為:

@Autowired
StringRedisTemplate stringRedisTemplate;

拓展:

1.SpringBoot 項目使用 Redis:

    ①`pom.xml` 添加依賴:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

    ②配置`application.properties` :

        #Redis服務器地址
        spring.redis.host=127.0.0.1
        #Redis服務器連接端口
        spring.redis.port=6379
        #Redis服務器連接密碼(默認為空)
        spring.redis.password=123456
        spring.redis.database=0

        #連接池最大連接數(shù)(使用負值表示沒有限制)
        spring.redis.jedis.pool.max-active=8
        #連接池中的最大空閑連接
        spring.redis.jedis.pool.max-idle=8
        #連接池中的最小空閑連接
        spring.redis.jedis.pool.min-idle=3
        #連接池最大阻塞等待時間(使用負值表示沒有限制)
        spring.redis.jedis.pool.max-wait=-1ms
        #連接超時時間(毫秒)
        spring.redis.timeout=30000

    ③注入,使用:
        
        @Autowired
        StringRedisTemplate stringRedisTemplate;

        stringRedisTemplate.opsForValue().set("key", "value");
        String value = stringRedisTemplate.opsForValue().get("key");
        System.out.println(value);

        stringRedisTemplate.opsForHash().entries("hash")

2.SpringBoot 項目使用 Redis,切換 Database 方法:

    LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) stringRedisTemplate.getConnectionFactory();
    if (connectionFactory != null) {
        connectionFactory.setDatabase(16);
        stringRedisTemplate.setConnectionFactory(connectionFactory);
        //connectionFactory.resetConnection(); //很多資料中執(zhí)行 resetConnection() 方法,不起作用
        connectionFactory.afterPropertiesSet(); //使用 afterPropertiesSet() 能正常切換
    }

注:SpringBoot 版本:2.2.8.RELEASE。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容