【问题标题】:Hibernate Search initialise index in multi-tenant Spring Boot application多租户 Spring Boot 应用程序中的 Hibernate Search 初始化索引
【发布时间】:2019-11-28 14:25:48
【问题描述】:

我有一个使用 Hibernate 的 Spring Boot 应用程序,我正在向它添加 Hibernate Search。该应用程序使用带有 Hibernate 的模式分离的多租户,实现 MultiTenantConnectionProviderCurrentTenantIdentifierResolver

我想在应用程序启动时创建初始搜索索引(或重新索引),以便能够搜索现有数据。

这是执行索引的服务:

@Service
public class SearchService {

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public void initializeSearchIndex() {

        try {
            FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
            fullTextEntityManager.createIndexer().startAndWait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

但问题是我不知道在哪里调用此服务。因为它使用EntityManager 而不是DataSource,所以它似乎与单个租户(数据库模式)相关联。有没有办法为整个数据库创建索引?如果是这样,在哪里调用它?

【问题讨论】:

    标签: spring-boot hibernate-search


    【解决方案1】:

    基本上,您需要为每个租户打开不同的会话(实体管理器)。您不能使用单一的跨租户质量索引器,因为这违背了多租户的概念:严格分离对每个租户数据的访问。

    我不知道使用 Spring boot 正确执行此操作的确切方法,但您的代码将如下所示:

    @Service
    public class SearchService {
    
        @PersistenceUnit
        private EntityManagerFactory entityManagerFactory;
    
        public void initializeSearchIndex() {
            SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
            for (String tenantId : getAllTenantIds()) {
                try (Session session = sessionFactory.withOptions().tenantIdentifier(tenantId).openSession()) {
                    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(session);
                    fullTextEntityManager.createIndexer().startAndWait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
        List<String> getAllTenantIds() {
             // return all tenant Ids
        }
    }
    

    【讨论】:

    • 谢谢,它有效。为了完整起见,我在创建 Session 对象时需要 .openSession()
    猜你喜欢
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2021-12-20
    • 1970-01-01
    • 2012-05-03
    相关资源
    最近更新 更多