项目依赖首先,在pom.xml中添加必要的依赖:
spring: data: elasticsearch: cluster-nodes: localhost:9200 cluster-name: my-application redis: host: localhost port: 6379商品实体类创建一个商品实体类:
import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Data @Document(indexName = "products") public class Product { @Id private String id; private String name; private String description; private Double price; private String category; // 其他字段 }Elasticsearch Repository创建一个Elasticsearch的Repository接口:
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; @Repository public interface ProductRepository extends ElasticsearchRepository
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.List; @Service public class RedisService { @Autowired private RedisTemplate
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.stereotype.Service; @Service public class ProductService { @Autowired private ProductRepository productRepository; @Autowired private ElasticsearchRestTemplate elasticsearchRestTemplate; @Autowired private RedisService redisService; public Page
import org.elasticsearch.search.sort.SortOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class ProductController { @Autowired private ProductService productService; @GetMapping("/search") public Page
注意事项Elasticsearch索引管理:在实际生产环境中,你可能需要更精细地管理Elasticsearch索引,包括映射、分词器等。缓存策略:这里的缓存策略非常简单,只是示例。实际项目中可能需要更复杂的缓存机制和策略。安全性:对于实际项目,请确保添加适当的安全措施,如身份验证和授权。性能优化:对于大规模数据,请确保对Elasticsearch和Redis进行适当的性能优化。