【问题标题】:Is it thread safe to change Mongo collection for Spring Data Repositories from static ThreadLocal variable?从静态 ThreadLocal 变量更改 Spring Data Repositories 的 Mongo 集合是否线程安全?
【发布时间】:2018-04-03 08:15:24
【问题描述】:

我想使用 Spring Data Mongo 存储库并在运行时指定文档的集合。 我在这张票DATAMONGO-525 中找到了实现它的方法以及我做了什么:

使用 ThreadLocal 变量创建 GenericObject 和链接集合名称 这个静态变量:

@Data
@Document(collection = "#{T(com.test.myproject.model.GenericObject).getCollection()}")
public class GenericObject {

    private static ThreadLocal<String> collection = new ThreadLocal<>();

    @Id
    private ObjectId id;

    private org.bson.Document doc;

    public static void setCollection(String type) {
        collection.set(type);
    }

    public static String getCollection() {
        return collection.get();
    }

}

我为 GenericObject 创建了 GenericRepository:

public interface GenericObjectRepository extends MongoRepository<GenericObject, ObjectId> {
}

所以,现在当我想从特定集合中获取/保存/删除 GenericObject 时,我应该在每个请求之前指定集合:

// save
GenericObject obj = new GenericObject();
GenericObject.setCollection(collectionName);
genericObjectRepository.save(obj)
...
//get
GenericObject.setCollection(collectionName);
genericObjectRepository.findById(new ObjectId(id))
                    .orElseThrow(() -> new RecordNotFoundException("GOS00001", id, collection));

问题是:

我的方法是线程安全的吗?有什么我看不到的问题吗?

SpringDataMongoDB 版本:2.0.5.RELEASE

【问题讨论】:

  • @OliverGierke,DATAMONGO-525 是最新版本吗?谢谢

标签: java mongodb spring-boot spring-data spring-data-mongodb


【解决方案1】:

听起来你最好直接使用MongoOperations。为什么要担心ThreadLocal。如果您想查看有关静态 ThreadLocal 使用的更多信息,您可以参考这个问题:Java ThreadLocal static? 但是是的,您的方法很好。 ThreadLocal 可以安全使用,因为不同的线程不能设置另一个线程的 ThreadLocal。

【讨论】:

  • 感谢@Strelok 的回答,挑战是在不使用 MongoTemplate 或 MongoOperations 实现 CRUD 操作的情况下使用 MongoRepositories。我只是想确定春天不会有任何副作用。
猜你喜欢
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 2011-07-07
相关资源
最近更新 更多