springboot篇】二十一. 基於springboot電商項目 三 整合docker配置fastdfs和solr

中國加油,武漢加油!

篇幅較長,配合目錄觀看

案例準備

  1. 本案例基於springboot篇】二十一. 基於springboot電商項目 二 模塊功能實現
  2. linux篇】九. Docker安裝
  3. linux篇】十. Docker安裝FastDFS和Solr

1. 測試FastDFS user-web(shop-back)

1.1 添加FastDFS依賴

<dependency>
	<groupId>com.github.tobato</groupId>
	<artifactId>fastdfs-client</artifactId>
	<version>1.26.1-RELEASE</version>
</dependency>

1.2 程序入口加入註解

package com.wpj;

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;

@SpringBootApplication(scanBasePackages = "com.wpj", exclude = DataSourceAutoConfiguration.class)
// FastDFS
@Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)
public class UserWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserWebApplication.class, args);
    }
}

1.3 配置yml

fdfs:
  tracker-list:
    - 192.168.1.114:22122
  connect-timeout: 2000
  so-timeout: 2000
  thumb-image:
    height: 300
    width: 300

1.4 TestFastDFS

package com.wpj;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.io.FileInputStream;

@SpringBootTest
@RunWith(SpringRunner.class)
class UserWebApplicationTests {

    @Autowired
    private FastFileStorageClient client;

    @Test
    void testFastDFS() throws Exception {
        // 準備上傳的文件
        File file = new File("E:\\codeDevelop\\ideaDevelop\\springboot\\nz1904-shop\\shop-web\\user-web\\src\\main\\resources\\static\\upload\\1.jpg");
        // 把文件轉成一個流
        FileInputStream fis = new FileInputStream(file);
        // 把圖片上傳到FastFDS
        StorePath storePath = client.uploadImageAndCrtThumbImage(fis, file.length(),"jpg",null);
        // 獲取圖片返回的路徑
        System.out.println(storePath.getFullPath());
    }
}

1.5 訪問圖片路徑

在這裏插入圖片描述

2 springboot整合fastdfs

2.1 修改yml

upload:
  FdfsPath: http://192.168.1.114:8080/

2.1 修改GoodsController

package com.wpj.controller;

import com.alibaba.dubbo.common.utils.IOUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.wpj.common.entity.ResultEntity;
import com.wpj.entity.Goods;
import com.wpj.service.IGoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Reference
    private IGoodService goodService;

    @RequestMapping("/getGoodsPage")
    public String getGoodsPage(Page<Goods> page, ModelMap map){
        page = goodService.getDubboPage(page);
        map.put("url", "goods/getGoodsPage");
        map.put("page",page);
        return "goods/goodsList";
    }

    @Autowired
    private FastFileStorageClient client;

    @Value("${upload.FdfsPath}")
    private String FdfsPath;

    private String uploadPath = "E:\\codeDevelop\\ideaDevelop\\springboot\\nz1904-shop\\shop-web\\user-web\\src\\main\\resources\\static\\upload";

    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(MultipartFile file){
        System.out.println("文件名:"+ file.getOriginalFilename());
        FileOutputStream os = null;
        InputStream is = null;
        File opsFile = new File(uploadPath+ File.separator+file.getOriginalFilename());

        String fileName = file.getOriginalFilename();
        String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1);
        StorePath storePath = null;
        try {
            storePath = client.uploadImageAndCrtThumbImage(file.getInputStream(), file.getSize(), fileExtName, null);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return FdfsPath+storePath.getFullPath();
    }
    
    @RequestMapping(value = "/addGoods")
    @ResponseBody
    public ResultEntity addGoods(Goods goods){
        // 1.把商品添加數據庫
        goodService.insert(goods);
        // 在這裏主鍵回填不過來,所以要在service層添加
        return ResultEntity.SUCCESS();
    }
}

2.3 訪問測試

在這裏插入圖片描述

3. 搭建前臺頁面

3.1 新建shop-front(module-springboot)

  1. Spring Boot DevTool
  2. Spring Web
  3. Thymeleaf

3.2 導入靜態資源

3.3 編寫index.html

3.4 編寫yml

server:
  port: 8081
spring:
  thymeleaf:
    cache: false
    prefix: classpath:/templates/

3.5 啓動程序入口

在這裏插入圖片描述

4. 搜索模塊

4.1 新建shop-search(module-springboot)

  1. Spring Boot DevTool
  2. Spring Web
  3. Thymeleaf

4.2 編寫yml

server:
  port: 8082

4.3 編寫Controller

package com.wpj.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/search")
public class SearchController {
    @RequestMapping("/searchGoods")
    @ResponseBody
    public String searchGoods(String key) {
        System.out.println("SearchController.searchGoods" + key);
        return "ok";
    }
}

4.4 修改程序入口

package com.wpj;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.wpj")
public class ShopSearchApplication {
    public static void main(String[] args) {
        SpringApplication.run(ShopSearchApplication.class, args);
    }
}

4.5 修改shop-front的index.html

<div class="srh">
    <form method="post" action="http://localhost:8082/search/searchGoods   ">
        <div class="ipt f-l">
            <input type="text" name="key" placeholder="搜索商品..." ss-search-show="sp" />
            <input type="text" placeholder="搜索店鋪..." ss-search-show="dp" style="display:none;" />
         </div>
        <button class="f-r">搜 索</button>
        <div style="clear:both;"></div>
    </form>
</div>

4.6 啓動8081和8082程序入口

在這裏插入圖片描述
在這裏插入圖片描述

5. springboot整合solr

5.1 新建shop-temp(module-maven)

5.1.1 刪掉src

5.2 shop-temp下新建solr-demo(module-springboot)

5.3 solr-demo導包

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-solr</artifactId>
   <version>2.1.7.RELEASE</version>
</dependency>

5.4 編寫yml

spring:
  data:
    solr:
      host: http://192.168.1.114:8983/solr/mycollection

5.5 TestAdd

package com.wpj;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
class SolrDemoApplicationTests {

    @Autowired
    private SolrClient solrClient;

    @Test
    public void testAdd() throws Exception{
        SolrInputDocument document = new SolrInputDocument();
        document.addField("gname","戴爾(DELL)成就3470 電腦");
        document.setField("gdesc","英特爾酷睿i3 商用辦公 臺式電腦整機(九代i3-9100 8G 1T 四年上門 鍵鼠 WIFI)21.5英寸");
        document.setField("gpic","xxx.png");
        document.setField("id","12");
        document.setField("gprice",3000.0);
        solrClient.add(document); // 如果id存在就會修改
        solrClient.commit(); // 事務提交
        System.out.println(solrClient);
    }
}

5.6 查詢

在這裏插入圖片描述

5.7 修改查詢數據的格式(匹配【linux篇】十. Docker安裝FastDFS和Solr的2.7配置solr字段域)

在這裏插入圖片描述

5.8 高光查詢

@Test
public void search()throws  Exception{
    String key ="Apple iPhone XR";
    String temp ="gname:%s || gdesc:%s";
    String format = String.format(temp, key, key);
    // 字段名稱:值
    SolrQuery solrQuery = new SolrQuery(format);
    solrQuery.setHighlight(true); // 開啓高亮
    solrQuery.addHighlightField("gname"); // 設置高亮的字段
    // 設置高亮的顏色
    solrQuery.setHighlightSimplePre("<font color='red'>");
    solrQuery.setHighlightSimplePost("</font>");
    QueryResponse queryResponse = solrClient.query(solrQuery);
    SolrDocumentList solrDocumentList = queryResponse.getResults(); // 得到結果集
    // 返回的是有高亮的結果集
    //<id,<高亮的字段,[值1,值2]>>
    Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
    for(SolrDocument document:solrDocumentList){
        String goodsId = document.getFieldValue("id").toString();
        // 判斷當前商是否有高亮的字段
        if(highlighting.get(goodsId) != null){
            // 獲取高亮的字段
            Map<String,List<String>> map = highlighting.get(goodsId);
            List<String> gname = map.get("gname");
            System.out.println(gname);
        }
    }
}

5.9 刪除與查詢

/**
 * 根據id查詢商品
 * @throws Exception
 */
@Test
public void testGetById() throws Exception{
    SolrDocument solrDocument = solrClient.getById("12");
    System.out.println("gname:"+solrDocument.get("gname")); // 根據key獲取value
    Collection<String> fieldNames = solrDocument.getFieldNames();// 獲取所有的字段名稱
    for(String filed:fieldNames){
        System.out.println(filed+":"+solrDocument.getFieldValue(filed)); // 屬性名稱
    }
    Map<String, Object> fieldValueMap = solrDocument.getFieldValueMap();
    System.out.println(fieldValueMap);
}

@Test
public void testDelete()throws  Exception{
//		solrClient.deleteById("12");
    solrClient.deleteByQuery("*:*");
    solrClient.commit();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章