5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring Data Redisでkeyの先頭に"\xac\xed\x00\x05t\x00\x05"が付与される問題

Last updated at Posted at 2020-04-24

概要

redis-cliで見ると存在しているkeyなのに、Spring Data Redisで見に行くとnilになるという事象に遭遇しました。
では、書き込みしてみたらどうなるか?をやってみたところ、謎の文字列がkey/valueともに付与されていることが確認できました。

前提

Redis 5.0.8
Spring Boot 2.2.6
Spring Data Redis 2.2.6

再現ソース

Javaソース

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

	@Autowired
	private RedisTemplate<String, String> template;

	@Resource(name = "redisTemplate")
	private ListOperations<String, String> listOps;

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

	@Override
	public void run(String... args) {
		Long result = listOps.leftPush("queue", "value1");
		System.out.println("value = " + result); // => 1
    }
}

redis-cli

127.0.0.1:6379> lpop "\xac\xed\x00\x05t\x00\x05queue"
"\xac\xed\x00\x05t\x00\x06value1"
127.0.0.1:6379>

原因

redis key/value 出现\xAC\xED\x00\x05t\x00\x05 - 春风十里的情 - 博客园
https://www.cnblogs.com/jiangds/p/9037553.html

によると、JdkSerializationRedisSerializerが悪さをしているそうです。

対策

上記サイトの通り、下記のおまじないを入れると直ります。

...
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.template = redisTemplate;
	}

	@Override
	public void run(String... args) {
...

ググっても中国語のサイトしかヒットしなかったので、マルチバイト文字を扱うところでしか問題が発生しないのかも知れませんね。

5
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?