简体   繁体   English

从静态ThreadLocal变量更改Spring数据存储库的Mongo集合是否安全?

[英]Is it thread safe to change Mongo collection for Spring Data Repositories from static ThreadLocal variable?

I wanted to use Spring Data Mongo repositories and specify collection of the document at runtime. 我想使用Spring Data Mongo存储库并在运行时指定文档的集合。 I found the way how I can achieve it in this ticket DATAMONGO-525 and what I did: 我在这张票DATAMONGO-525中找到了实现该目标的方法以及我所做的事情:

Created GenericObject with ThreadLocal variable and linked collection name with this static variable: 使用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();
    }

}

I created GenericRepository for GenericObject: 我为GenericObject创建了GenericRepository:

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

So, now when I want to get/save/delete GenericObject from specific collection I should specify collection before each request: 因此,现在,当我想从特定集合中获取/保存/删除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));

The question is: 问题是:

Is my approach is thread safe? 我的方法是线程安全的吗? Are there any issues that I don't see? 有没有我看不到的问题?

SpringDataMongoDB version: 2.0.5.RELEASE SpringDataMongoDB版本: 2.0.5.RELEASE

Sounds like you're almost better off just using MongoOperations directly. 听起来,直接使用MongoOperations几乎可以使您感觉更好。 Why bother with worrying with ThreadLocal . 为什么还要担心ThreadLocal If you want to see more info about static ThreadLocal usage you can refer to this question: Java ThreadLocal static? 如果要查看有关静态ThreadLocal用法的更多信息,可以参考以下问题: Java ThreadLocal static? But yeah you're approach is fine. 但是,是的,您的做法很好。 ThreadLocal is safe to use as a different thread can't set ThreadLocal of another thread. 可以安全地使用ThreadLocal,因为其他线程无法设置另一个线程的ThreadLocal。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM