[백업][가리사니] 스프링 solr 연동
java, solr, spring
이 문서는 가리사니 개발자 포럼에 올렸던 글의 백업 파일입니다. 오래된 문서가 많아 현재 상황과 맞지 않을 수 있습니다.
솔라의 설치 및 사용법에 대해서는 아래 링크를 참조해주세요. 검색엔진 솔라 시작하기 /2016/04/26/%EB%B0%B1%EC%97%85-%EA%B0%80%EB%A6%AC%EC%82%AC%EB%8B%88-%EA%B2%80%EC%83%89%EC%97%94%EC%A7%84-%EC%86%94%EB%9D%BC-%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0.html
스프링 부트 1.4.x 부터는 설정법이 조금 달라집니다.
1. pom.xml 설정
- 솔라를 추가해줍니다.
- http://projects.spring.io/spring-data-solr/
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
</dependency>
2. application.properties 작성
- 소스에 하드코딩 할 수 있지만, 관리파일을 따로두는 것을 좋아하기 때문에 이곳에 적겠습니다.
# 이름은 적당히 정해주시면됩니다.
spring.conn_solr_test_1.host=http://<호스트>:<포트>/solr
3. 연결설정
- 연동할 솔라가 1개일 경우에는 basePackages, solrServerRef 를 생략 가능하지만.
- 여러개의 솔라가 있다는 가정하에 경로를 지정하여 설정해보았습니다.
@Configuration
// com.web.repository.solr1 내에속한 리포지토리는 solr1 의 빈으로 연동
@EnableSolrRepositories
(
basePackages="com.web.repository.solr1",
solrServerRef="solr1",
multicoreSupport=true
)
public class Solr1Config
{
@Resource
private Environment environment;
@Bean(name = "solr1")
public SolrServer solrServer()
{
return new HttpSolrServer(environment.getRequiredProperty("spring.conn_solr_test_1.host"));
}
}
4. 데이터
- 코어 이름은 Tag로 써봤습니다.
- Tag대신 다른걸 대입해서 써보시기 바랍니다. (절대 고치기 귀찮아서가 아닙니다. 하하하하)
- 롬복 : /wiki?dn=70
// 위 설정에서 알수있듯 basePackages="com.web.repository.solr1" 와 연동
package com.web.domain.solr1;
import org.apache.solr.client.solrj.beans.Field;
import org.springframework.data.annotation.Id;
import org.springframework.data.solr.core.mapping.SolrDocument;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
// 롬복사용
@Data
@SolrDocument(solrCoreName = "코어이름")
@Getter @Setter
public class Tag
{
// 주의할점 id는 org.springframework.data.annotation.Id 를 이용해야함.
// import javax.persistence.Id; 사용시 오류
@Id
// 필드는 컬럼(javax.persistence.Column)이 아닌 필드(org.apache.solr.client.solrj.beans.Field)를 써야합니다.
@Field
private long 아이디필드;
@Field
private String 일반필드;
}
5. 리포지토리
- 리포지토리도 조금 다른 SolrCrudRepository 를 사용합니다.
- 각종 쿼리 옵션등은 아래 주소에서 참고해 볼 수 있습니다.
- http://docs.spring.io/spring-data/solr/docs/current/reference/html/
public interface TagRepository extends SolrCrudRepository<Tag, String>
{
@Query(value = "*:*", filters = { "" })
Page<Tag> findAll(Pageable pageable);
}
6. 서비스
- @EnableSolrRepositories의 설정으로 자동으로 @Autowired 됩니다.
- 인터넷 예제를 보면 @Autowired 대신 유독 @Resource 가 많은데.. @EnableSolrRepositories 로 지정되어 @Resource 를 써도 무방합니다.
- 자세한건 @Autowired, @Resource 차이점을 검색해보세요.
@Service
public class TagService
{
@Autowired
TagRepository tagRepository;
public Page<Tag> findAll(Pageable pageable)
{
return tagRepository.findAll(pageable);
}
}
7. 컨트롤러 (테스트)
- 일반적인 리포지토리 처럼 사용할 수 있다는 것을 보여주기위한 예제..
@Controller
@Controller("tag")
public class SolrController
{
@Autowired
TagService tagService;
@RequestMapping(method = RequestMethod.GET)
Page<Tag> list(Model model)
{
Pageable pageable = new PageRequest(0, 10);
Page<Tag> tsgs = tagService.findAll(pageable);
return tsgs;
}
}