Commit 08625b0c authored by macro's avatar macro
Browse files

升级SpringBoot 2.3.0

parent 6a9f1202
package com.macro.mall.search.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger API文档相关配置
* Created by macro on 2018/4/26.
*/
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.macro.mall.search.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("mall搜索系统")
.description("mall搜索模块")
.contact("macro")
.version("1.0")
.build();
}
}
package com.macro.mall.search.config;
import com.macro.mall.common.config.BaseSwaggerConfig;
import com.macro.mall.common.domain.SwaggerProperties;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger2API文档的配置
* Created by macro on 2018/4/26.
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig extends BaseSwaggerConfig {
@Override
public SwaggerProperties swaggerProperties() {
return SwaggerProperties.builder()
.apiBasePackage("com.macro.mall.search.controller")
.title("mall搜索系统")
.description("mall搜索相关接口文档")
.contactName("macro")
.version("1.0")
.enableSecurity(false)
.build();
}
}
...@@ -5,7 +5,6 @@ import com.macro.mall.search.domain.EsProduct; ...@@ -5,7 +5,6 @@ import com.macro.mall.search.domain.EsProduct;
import com.macro.mall.search.domain.EsProductRelatedInfo; import com.macro.mall.search.domain.EsProductRelatedInfo;
import com.macro.mall.search.repository.EsProductRepository; import com.macro.mall.search.repository.EsProductRepository;
import com.macro.mall.search.service.EsProductService; import com.macro.mall.search.service.EsProductService;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery; import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
...@@ -14,10 +13,10 @@ import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders; ...@@ -14,10 +13,10 @@ import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.Aggregation; import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.filter.InternalFilter; import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter;
import org.elasticsearch.search.aggregations.bucket.nested.InternalNested; import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms; import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms; import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.search.sort.SortOrder;
...@@ -28,7 +27,10 @@ import org.springframework.data.domain.Page; ...@@ -28,7 +27,10 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -39,6 +41,7 @@ import java.util.ArrayList; ...@@ -39,6 +41,7 @@ import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
/** /**
...@@ -53,7 +56,7 @@ public class EsProductServiceImpl implements EsProductService { ...@@ -53,7 +56,7 @@ public class EsProductServiceImpl implements EsProductService {
@Autowired @Autowired
private EsProductRepository productRepository; private EsProductRepository productRepository;
@Autowired @Autowired
private ElasticsearchTemplate elasticsearchTemplate; private ElasticsearchRestTemplate elasticsearchRestTemplate;
@Override @Override
public int importAll() { public int importAll() {
List<EsProduct> esProductList = productDao.getAllEsProductList(null); List<EsProduct> esProductList = productDao.getAllEsProductList(null);
...@@ -157,7 +160,12 @@ public class EsProductServiceImpl implements EsProductService { ...@@ -157,7 +160,12 @@ public class EsProductServiceImpl implements EsProductService {
nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC)); nativeSearchQueryBuilder.withSort(SortBuilders.scoreSort().order(SortOrder.DESC));
NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build(); NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
LOGGER.info("DSL:{}", searchQuery.getQuery().toString()); LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
return productRepository.search(searchQuery); SearchHits<EsProduct> searchHits = elasticsearchRestTemplate.search(searchQuery, EsProduct.class);
if(searchHits.getTotalHits()<=0){
return new PageImpl<>(null,pageable,0);
}
List<EsProduct> searchProductList = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
return new PageImpl<>(searchProductList,pageable,searchHits.getTotalHits());
} }
@Override @Override
...@@ -196,7 +204,12 @@ public class EsProductServiceImpl implements EsProductService { ...@@ -196,7 +204,12 @@ public class EsProductServiceImpl implements EsProductService {
builder.withPageable(pageable); builder.withPageable(pageable);
NativeSearchQuery searchQuery = builder.build(); NativeSearchQuery searchQuery = builder.build();
LOGGER.info("DSL:{}", searchQuery.getQuery().toString()); LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
return productRepository.search(searchQuery); SearchHits<EsProduct> searchHits = elasticsearchRestTemplate.search(searchQuery, EsProduct.class);
if(searchHits.getTotalHits()<=0){
return new PageImpl<>(null,pageable,0);
}
List<EsProduct> searchProductList = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());
return new PageImpl<>(searchProductList,pageable,searchHits.getTotalHits());
} }
return new PageImpl<>(null); return new PageImpl<>(null);
} }
...@@ -225,16 +238,14 @@ public class EsProductServiceImpl implements EsProductService { ...@@ -225,16 +238,14 @@ public class EsProductServiceImpl implements EsProductService {
.field("attrValueList.name")))); .field("attrValueList.name"))));
builder.addAggregation(aggregationBuilder); builder.addAggregation(aggregationBuilder);
NativeSearchQuery searchQuery = builder.build(); NativeSearchQuery searchQuery = builder.build();
return elasticsearchTemplate.query(searchQuery, response -> { SearchHits<EsProduct> searchHits = elasticsearchRestTemplate.search(searchQuery, EsProduct.class);
LOGGER.info("DSL:{}",searchQuery.getQuery().toString()); return convertProductRelatedInfo(searchHits);
return convertProductRelatedInfo(response);
});
} }
/** /**
* 将返回结果转换为对象 * 将返回结果转换为对象
*/ */
private EsProductRelatedInfo convertProductRelatedInfo(SearchResponse response) { private EsProductRelatedInfo convertProductRelatedInfo(SearchHits<EsProduct> response) {
EsProductRelatedInfo productRelatedInfo = new EsProductRelatedInfo(); EsProductRelatedInfo productRelatedInfo = new EsProductRelatedInfo();
Map<String, Aggregation> aggregationMap = response.getAggregations().getAsMap(); Map<String, Aggregation> aggregationMap = response.getAggregations().getAsMap();
//设置品牌 //设置品牌
...@@ -253,14 +264,14 @@ public class EsProductServiceImpl implements EsProductService { ...@@ -253,14 +264,14 @@ public class EsProductServiceImpl implements EsProductService {
productRelatedInfo.setProductCategoryNames(productCategoryNameList); productRelatedInfo.setProductCategoryNames(productCategoryNameList);
//设置参数 //设置参数
Aggregation productAttrs = aggregationMap.get("allAttrValues"); Aggregation productAttrs = aggregationMap.get("allAttrValues");
List<LongTerms.Bucket> attrIds = ((LongTerms) ((InternalFilter) ((InternalNested) productAttrs).getProperty("productAttrs")).getProperty("attrIds")).getBuckets(); List<? extends Terms.Bucket> attrIds = ((ParsedLongTerms) ((ParsedFilter) ((ParsedNested) productAttrs).getAggregations().get("productAttrs")).getAggregations().get("attrIds")).getBuckets();
List<EsProductRelatedInfo.ProductAttr> attrList = new ArrayList<>(); List<EsProductRelatedInfo.ProductAttr> attrList = new ArrayList<>();
for (Terms.Bucket attrId : attrIds) { for (Terms.Bucket attrId : attrIds) {
EsProductRelatedInfo.ProductAttr attr = new EsProductRelatedInfo.ProductAttr(); EsProductRelatedInfo.ProductAttr attr = new EsProductRelatedInfo.ProductAttr();
attr.setAttrId((Long) attrId.getKey()); attr.setAttrId((Long) attrId.getKey());
List<String> attrValueList = new ArrayList<>(); List<String> attrValueList = new ArrayList<>();
List<StringTerms.Bucket> attrValues = ((StringTerms) attrId.getAggregations().get("attrValues")).getBuckets(); List<? extends Terms.Bucket> attrValues = ((ParsedStringTerms) attrId.getAggregations().get("attrValues")).getBuckets();
List<StringTerms.Bucket> attrNames = ((StringTerms) attrId.getAggregations().get("attrNames")).getBuckets(); List<? extends Terms.Bucket> attrNames = ((ParsedStringTerms) attrId.getAggregations().get("attrNames")).getBuckets();
for (Terms.Bucket attrValue : attrValues) { for (Terms.Bucket attrValue : attrValues) {
attrValueList.add(attrValue.getKeyAsString()); attrValueList.add(attrValue.getKeyAsString());
} }
......
...@@ -16,4 +16,14 @@ spring: ...@@ -16,4 +16,14 @@ spring:
elasticsearch: elasticsearch:
repositories: repositories:
enabled: true enabled: true
cluster-nodes: 127.0.0.1:9300 elasticsearch:
\ No newline at end of file rest:
uris: localhost:9200
logging:
level:
root: info
com.macro.mall: debug
logstash:
host: localhost
\ No newline at end of file
...@@ -12,12 +12,20 @@ spring: ...@@ -12,12 +12,20 @@ spring:
stat-view-servlet: #访问监控网页的登录用户名和密码 stat-view-servlet: #访问监控网页的登录用户名和密码
login-username: druid login-username: druid
login-password: druid login-password: druid
data: data:
elasticsearch: elasticsearch:
repositories: repositories:
enabled: true enabled: true
cluster-nodes: es:9300 elasticsearch:
rest:
uris: es:9200
logging: logging:
path: /var/logs #配置日志生成路径 file:
path: /var/logs
level:
root: info
com.macro.mall: info
logstash:
host: logstash
\ No newline at end of file
spring: spring:
application:
name: mall-search
profiles: profiles:
active: dev #默认为开发环境 active: dev #默认为开发环境
...@@ -10,10 +12,5 @@ mybatis: ...@@ -10,10 +12,5 @@ mybatis:
- classpath:dao/*.xml - classpath:dao/*.xml
- classpath*:com/**/mapper/*.xml - classpath*:com/**/mapper/*.xml
logging:
level:
root: info
com.macro.mall: debug
...@@ -2,14 +2,12 @@ package com.macro.mall.search; ...@@ -2,14 +2,12 @@ package com.macro.mall.search;
import com.macro.mall.search.dao.EsProductDao; import com.macro.mall.search.dao.EsProductDao;
import com.macro.mall.search.domain.EsProduct; import com.macro.mall.search.domain.EsProduct;
import com.macro.mall.search.repository.EsProductRepository;
import org.elasticsearch.action.search.SearchResponse;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.ResultsExtractor; import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import java.util.List; import java.util.List;
...@@ -21,7 +19,7 @@ public class MallSearchApplicationTests { ...@@ -21,7 +19,7 @@ public class MallSearchApplicationTests {
@Autowired @Autowired
private EsProductDao productDao; private EsProductDao productDao;
@Autowired @Autowired
private ElasticsearchTemplate elasticsearchTemplate; private ElasticsearchRestTemplate elasticsearchTemplate;
@Test @Test
public void contextLoads() { public void contextLoads() {
} }
...@@ -32,8 +30,9 @@ public class MallSearchApplicationTests { ...@@ -32,8 +30,9 @@ public class MallSearchApplicationTests {
} }
@Test @Test
public void testEsProductMapping(){ public void testEsProductMapping(){
elasticsearchTemplate.putMapping(EsProduct.class); IndexOperations indexOperations = elasticsearchTemplate.indexOps(EsProduct.class);
Map mapping = elasticsearchTemplate.getMapping(EsProduct.class); indexOperations.putMapping(indexOperations.createMapping(EsProduct.class));
Map mapping = indexOperations.getMapping();
System.out.println(mapping); System.out.println(mapping);
} }
......
package com.macro.mall.security.config; package com.macro.mall.security.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.macro.mall.common.config.BaseRedisConfig;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/** /**
* Redis相关配置 * Redis配置
* Created by macro on 2020/3/2. * Created by macro on 2020/3/2.
*/ */
@EnableCaching @EnableCaching
@Configuration @Configuration
public class RedisConfig extends CachingConfigurerSupport { public class RedisConfig extends BaseRedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisSerializer<Object> serializer = redisSerializer();
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(serializer);
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(serializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public RedisSerializer<Object> redisSerializer() {
//创建JSON序列化器
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(objectMapper);
return serializer;
}
@Bean
public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//设置Redis缓存有效期为1天
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofDays(1));
return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
}
} }
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7.RELEASE</version> <version>2.3.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository --> <relativePath/> <!-- lookup parent from repository -->
</parent> </parent>
...@@ -42,11 +42,11 @@ ...@@ -42,11 +42,11 @@
<swagger-annotations.version>1.6.0</swagger-annotations.version> <swagger-annotations.version>1.6.0</swagger-annotations.version>
<mybatis-generator.version>1.3.7</mybatis-generator.version> <mybatis-generator.version>1.3.7</mybatis-generator.version>
<mybatis.version>3.4.6</mybatis.version> <mybatis.version>3.4.6</mybatis.version>
<mysql-connector.version>8.0.16</mysql-connector.version> <mysql-connector.version>8.0.15</mysql-connector.version>
<spring-data-commons.version>2.1.5.RELEASE</spring-data-commons.version> <spring-data-commons.version>2.3.0.RELEASE</spring-data-commons.version>
<jjwt.version>0.9.0</jjwt.version> <jjwt.version>0.9.0</jjwt.version>
<aliyun-oss.version>2.5.0</aliyun-oss.version> <aliyun-oss.version>2.5.0</aliyun-oss.version>
<logstash-logback.version>4.8</logstash-logback.version> <logstash-logback.version>5.3</logstash-logback.version>
<minio.version>3.0.10</minio.version> <minio.version>3.0.10</minio.version>
<guava.version>20.0</guava.version> <guava.version>20.0</guava.version>
<mall-common.version>1.0-SNAPSHOT</mall-common.version> <mall-common.version>1.0-SNAPSHOT</mall-common.version>
...@@ -55,10 +55,6 @@ ...@@ -55,10 +55,6 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId> <artifactId>spring-boot-starter-actuator</artifactId>
...@@ -73,12 +69,17 @@ ...@@ -73,12 +69,17 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.github.pagehelper</groupId> <groupId>cn.hutool</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId> <artifactId>hutool-all</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.alibaba</groupId> <groupId>org.projectlombok</groupId>
<artifactId>druid-spring-boot-starter</artifactId> <artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency> </dependency>
</dependencies> </dependencies>
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment