涉及微服務:
changgou_web_search:存放靜態資源,實現頁面跳轉。
changgou_service_search:負責從ES查詢數據。
changgou_service_search_api:放實體對象及feign接口。
(1)創建changgou_web_search工程
pom的引入(前端使用的是thymeleaf模板引擎)
<dependencies>
<dependency>
<groupId>com.changgou</groupId>
<artifactId>changgou_common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.changgou</groupId>
<artifactId>changgou_service_search_api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--thymeleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
存放靜態資源創建類:
這裏注意static與templates文件夾名必須這樣起,不然需要配置,麻煩!
application.yml的配置:
server:
port: 9011
spring:
application:
name: webSearch
main:
allow-bean-definition-overriding: true #當遇到同樣名字的時候,是否允許覆蓋註冊
thymeleaf:
cache: false #thymeleaf數據緩存關閉
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:6868/eureka
instance:
prefer-ip-address: true
feign:
hystrix:
enabled: true
client:
config:
default: #配置全局的feign的調用超時時間 如果 有指定的服務配置 默認的配置不會生效
connectTimeout: 60000 # 指定的是 消費者 連接服務提供者的連接超時時間 是否能連接 單位是毫秒
readTimeout: 80000 # 指定的是調用服務提供者的 服務 的超時時間() 單位是毫秒
#hystrix 配置
hystrix:
command:
default:
execution:
timeout:
#如果enabled設置爲false,則請求超時交給ribbon控制
enabled: true
isolation:
strategy: SEMAPHORE
thread:
# 熔斷器超時時間,默認:1000/毫秒
timeoutInMilliseconds: 80000
websearchController:
package com.changgou.web.search.controller;
import com.changgou.entity.Page;
import com.changgou.web.search.service.WebSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
import java.util.Set;
/**
* @author :gzy
* @date :Created in 2019/8/20
* @description :
* @version: 1.0
*/
@Controller
@RequestMapping("/wsearch")
public class WebSearchController {
@Autowired
private WebSearchService webSearchService;
@GetMapping
public String searchGoods(Model model,@RequestParam Map<String,String> searchmap){
Map map = webSearchService.searchSkuInfoByEs(searchmap);
model.addAttribute("result",map);
model.addAttribute("searchMap",searchmap);
model.addAttribute("page",new Page((int)map.get("total"),Integer.valueOf(map.get("pageNum").toString()),Page.pageSize));
//http://search.changgou.com:9011/wsearch?keywords=手機
StringBuilder url = new StringBuilder();
url.append("http://search.changgou.com:9011/wsearch");
if(null!=searchmap&&searchmap.size()>0){
url.append("?");
Set<Map.Entry<String, String>> entries = searchmap.entrySet();
for (Map.Entry<String, String> entry : entries) {
if(!"pageNum".equals(entry.getKey())){
url.append("&").append(entry.getKey()).append("=").append(entry.getValue());
}
}
}
model.addAttribute("url",url.toString());
return "search";
}
}
WebSearchService 實現類及接口省略,實現類主要通過Feign調用changgou_service_search微服務的查詢功能。
(2)changgou_service_search工程
搜索功能實現類:
/**
* @author :gzy
* @date :Created in 2019/8/19
* @description :
* @version: 1.0
*/
@Service
public class SearchServiceImpl implements SearchService {
@Autowired
private EsMapper esMapper;
@Autowired
private GoodsFeign goodsFeign;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
//從 數據庫導入數據到Es
@Override
public void importData() {
//創建索引
elasticsearchTemplate.createIndex(SkuInfo.class);
//設置映射
elasticsearchTemplate.putMapping(SkuInfo.class);
List<Sku> byStatus = goodsFeign.findByStatus("1");
String string = JSON.toJSONString(byStatus);
List<SkuInfo> skuInfos = JSON.parseArray(string, SkuInfo.class);
for (SkuInfo skuInfo : skuInfos) {
skuInfo.setSpecMap(JSON.parseObject(skuInfo.getSpec(),Map.class));
}
esMapper.saveAll(skuInfos);
}
//搜索功能
@Override
public Map searchSkuInfoByEs(Map<String, String> searchmap) {
Map map=new HashMap<>();
//條件對象 目標:爲了合併 搜索條件及排序及分頁及高亮
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
//組合條件對象
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//本次查詢關鍵詞
if(null!=searchmap.get("keywords") && !"".equals(searchmap.get("keywords").trim())){
boolQueryBuilder.must(QueryBuilders.matchQuery("name",searchmap.get("keywords")));
}
else {
//默認搜索條件
}
//分頁
String pageNum=searchmap.get("pageNum");
if(StringUtils.isEmpty(pageNum)){
pageNum="1";
}
nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.valueOf(pageNum)-1,Page.pageSize));
nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
AggregatedPage<SkuInfo> page = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class);
List<SkuInfo> content = page.getContent();
//查詢到的數據
map.put("rows",content);
//當前頁
map.put("pageNum",pageNum);
//數據總條數
map.put("total",page.getTotalElements());
return map;
}
}
searcController:
package com.changgou.search.controller;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.security.cert.TrustAnchor;
import java.util.Map;
/**
* @author :gzy
* @date :Created in 2019/8/19
* @description :
* @version: 1.0
*/
@RestController
@CrossOrigin
@RequestMapping("/search")
public class SearchController {
@Autowired
private SearchService searchService;
/*
搜索,被遠程調用
*/
@GetMapping("/list")
public Map search(@RequestParam Map<String,String> searchmap){
return searchService.searchSkuInfoByEs(searchmap);
}
//導入數據
@GetMapping("/importData")
public Result importData(){
searchService.saveall();
return new Result(true,StatusCode.OK,"導入成功");
}
}
(3)changgou_service_search_api
暴露的feign接口:
package com.changgou.search.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
/**
* @author :gzy
* @date :Created in 2019/8/20
* @description :
* @version: 1.0
*/
@FeignClient(name = "search")
@RequestMapping("/search")
public interface SearchFeign {
@GetMapping("/list")
Map search(@RequestParam(name = "searchmap") Map<String,String> searchmap);
}