小编典典

Spring Boot Standard UUID编解码器不适用于AbstractMongoClientConfiguration

spring-boot

我升级到Spring Boot
2.2.0.RELEASE,并想用AbstractMongoClientConfiguration替换现在不推荐使用的AbstractMongoConfiguration。我在用

codecRegistries.add(CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)));

将MongoDB中的UUID编解码器设置为STANDARD(UUID),而不是Legacy
Codec(LUUID)。当查询数据库时,编解码器将保持旧格式。还有其他人遇到过同样的问题吗?

旧的实现方式(有效):

@Override
public MongoClient mongoClient() {
CodecRegistry codecRegistry =
                CodecRegistries.fromRegistries(CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)),
                        MongoClient.getDefaultCodecRegistry());
        return new MongoClient(new ServerAddress(address, port), MongoClientOptions.builder().codecRegistry(codecRegistry).build());
}

新的实现(不起作用):

@Override
public MongoClient mongoClient() {
        List<CodecRegistry> codecRegistries = new ArrayList<>();
        codecRegistries.add(CodecRegistries.fromCodecs(new DocumentCodec()));
        codecRegistries.add(CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)));
        CodecRegistry codecRegistry = CodecRegistries.fromRegistries(codecRegistries);

        return MongoClients.create(MongoClientSettings.builder()
                                                      .codecRegistry(codecRegistry)
                                                      .applyConnectionString(new ConnectionString(connectionString))
                                                      .build());
}

我希望数据库中的UUID编解码器可以调整为标准编解码器,但仍保留在旧版编解码器中。


阅读 831

收藏
2020-05-30

共1个答案

小编典典

我找到了解决问题的办法。该new UuidCodec(UuidRepresentation.STANDARD)需求是在第一的位置。我的代码如下所示:

    private static final CodecRegistry CODEC_REGISTRY = CodecRegistries.fromProviders(
        Arrays.asList(new UuidCodecProvider(UuidRepresentation.STANDARD),
                      new ValueCodecProvider(),
                      new BsonValueCodecProvider(),
                      new DBRefCodecProvider(),
                      new DBObjectCodecProvider(),
                      new DocumentCodecProvider(new DocumentToDBRefTransformer()),
                      new IterableCodecProvider(new DocumentToDBRefTransformer()),
                      new MapCodecProvider(new DocumentToDBRefTransformer()),
                      new GeoJsonCodecProvider(),
                      new GridFSFileCodecProvider(),
                      new Jsr310CodecProvider(),
                      new BsonCodecProvider()));

这种行为不是很好,并且可能是一个错误。希望对您有所帮助。

2020-05-30