Как реализовать собственный репозиторий Solr с использованием Spring Data Solr для нескольких ядер и репозиториев

Я хочу иметь доступ к нескольким репозиториям /2 в одном сервисе, используя spring-data-solr. Из Spring Data Solr для нескольких ядер и репозитория я знаю, что "многоядерная поддержка через конфигурацию пространства имен, к сожалению, остается открытой".

Можете ли вы помочь мне с приведенным ниже примером, как я могу создать собственные Repos?

В моем applicationContext.xml есть два шаблона Solr, которые определены ниже:

<!-- Enable Solr repositories and configure repository base package -->
<solr:repositories base-package="com.ay.api.repository"/>

<!-- Configures HTTP Solr server -->
<solr:solr-server id="solrServer" url="${solr.server.url}"/>

<!-- Configures Solr Events template -->
   <bean id="solrEventsTemplate" class="org.springframework.data.solr.core.SolrTemplate">
   <qualifier type="solrEventsTemplate"/>
   <constructor-arg index="0" ref="solrServer"/>
   <constructor-arg index="1" value="${solr.server.events.core.name}"/>
</bean>

<!-- Configures Solr Towns template -->
<bean id="solrTownsTemplate" class="org.springframework.data.solr.core.SolrTemplate">
<constructor-arg index="0" ref="solrServer"/>
<constructor-arg index="1" value="${solr.server.towns.core.name}"/>
</bean>

и у меня есть следующие репо

@Repository
public class EventDocumentRepositoryImpl implements EventSearchRepository { 


@Resource
@Qualifier("solrEventsTemplate")
private SolrTemplate solrEventsTemplate;

...
}

public interface EventDocumentRepository extends EventSearchRepository, SolrCrudRepository<EventDocument, String> {

}

public interface EventSearchRepository { .... }


@Repository
public class TownRepositoryImpl implements TownSearchRepository { ... 

@Resource
@Qualifier("solrTownsTemplate")
private SolrTemplate solrTownsTemplate;

...
}

public interface TownRepository extends SolrCrudRepository<TownDocument, String>{}
public interface TownSearchRepository { .... }

и, наконец, сервис выглядит следующим образом:

 @Service
 public class SearchEventServiceImpl implements SearchEventService {

 @Resource
 private EventDocumentRepository eventRepository;

 @Resource
 private TownRepository townRepository;
 .....
 }

Кто-то может посоветовать, как мне изменить мой код для реализации пользовательских репозиториев, как указано в Spring Data Solr с многоядерным Solr 4.1? как я не мог понять предложенное решение в этой теме.

Спасибо заранее.

2 ответа

Решение

Сканирование репозитория будет искать solrTemplate и создайте репозиторий, используя предоставленный шаблон. Так как вам нужен один шаблон для каждого ядра Solr, вам придется создавать оба шаблона, и репозиторий вручную.

Сначала создайте свои репозитории и пользовательские реализации.

public interface EventRepositoryCustom {

    Page<Event> findEvent();

}

public interface EventRepository extends EventRepositoryCustom, SolrCrudRepository<Event, String> {

}

public class EventRepositoryImpl implements EventRepositoryCustom {

    private SolrTemplate eventTemplate;

    public EventRepositoryImpl(SolrTemplate eventTemplate) {
        this.eventTemplate = eventTemplate;
    }

    @Override
    public Page<Event> findEvent() {
        return eventTemplate.queryForPage(new SimpleQuery("*:*"), Event.class);
    }

}

Сделайте то же самое для вашего TownRepository,

Использование Java Config для конфигурации. То же самое можно сделать с XML.

@Configuration
public class SolrContext {

  private static final String PROPERTY_NAME_SOLR_SERVER_URL = "solr.host";

  @Resource
  private Environment environment;

  // Factory creates SolrServer instances for base url when requesting server
  // for specific core. 
  @Bean
  public SolrServerFactory solrServerFactory() {
    return new MulticoreSolrServerFactory(new HttpSolrServer(
            environment.getRequiredProperty(PROPERTY_NAME_SOLR_SERVER_URL)));
  }

  // SolrTemplate for /solrServerUrl/towns
  @Bean
  public SolrTemplate townTemplate() throws Exception {
    SolrTemplate solrTemplate = new SolrTemplate(solrServerFactory());
    solrTemplate.setSolrCore("towns");
    return solrTemplate;
  }

  // SolrTemplate for /solrServerUrl/events
  @Bean
  public SolrTemplate eventTemplate() throws Exception {
    SolrTemplate solrTemplate = new SolrTemplate(solrServerFactory());
    solrTemplate.setSolrCore("events");
    return solrTemplate;
  }

  @Bean
  public EventRepository eventRepository() throws Exception {
    return new SolrRepositoryFactory(eventTemplate())
      .getRepository(EventRepository.class, new EventRepositoryImpl(eventTemplate()));
  }

  @Bean
  public TownRepository townRepository() throws Exception {
    return new SolrRepositoryFactory(townTemplate())
      .getRepository(TownRepository.class, new TownRepositoryImpl(townTemplate()));
  }
}

Когда я сделал это, как предлагается в ответе, я получил исключение PersistenceExceptionTranslator, поэтому я инициализирую этот компонент вручную:

<beans:bean id="PersistenceExceptionTranslator" class="org.springframework.data.solr.core.SolrExceptionTranslator"/>
Другие вопросы по тегам