Browse Source

第三次更新
(
"ES搜索"
Mongo搜索记录保存

)

杨旭朋 2 weeks ago
parent
commit
c37990ba01

+ 1 - 19
src/main/java/com/futu/course/course/service/impl/CourseCategoryServiceImpl.java

@@ -5,27 +5,9 @@ import com.futu.course.course.domain.CourseCategory;
 import com.futu.course.course.service.CourseCategoryService;
 import com.futu.course.course.mapper.CourseCategoryMapper;
 import org.springframework.stereotype.Service;
-
-import java.util.List;
-
-/**
- * @author yuu
- * @description 针对表【course_category】的数据库操作Service实现
- * @createDate 2025-05-05 18:45:13
- */
 @Service
 public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {
-    /**
-     * @title: CourseCategoryList
-     * @desc: 查看所有的分类
-     * @params ()
-     * @return: List<CourseCategory>
-     * @author: 杨旭朋
-     * @date: 2025/5/6 18:42
-     */
-    public List<CourseCategory> CourseCategoryList() {
-        return this.list();
-    }
+
 }
 
 

+ 3 - 36
src/main/java/com/futu/course/course/service/impl/CourseServiceImpl.java

@@ -4,12 +4,9 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import com.futu.course.course.domain.Course;
 import com.futu.course.course.service.CourseService;
 import com.futu.course.course.mapper.CourseMapper;
-import com.futu.course.course.vo.CourseVo;
+
 import org.springframework.stereotype.Service;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.WeakHashMap;
 
 /**
  * @author yuu
@@ -18,38 +15,8 @@ import java.util.WeakHashMap;
  */
 @Service
 public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
-/**
- * @title: CourseList
- * @desc:  数据分类
- * @params List<CourseVo>
- * @return: int categoryId
- * @author: 杨旭朋
- * @date: 2025/5/6 19:03
- */
-    public List<CourseVo> CourseList(int categoryId) {
-//        初始化数据
-        List<CourseVo> courseVos = new ArrayList<>();
-        for (Course course : this.list()) {
-            CourseVo courseVo = new CourseVo();
-            courseVo.setId(course.getId());
-            courseVo.setCategoryId(course.getCategoryId());
-            courseVo.setTitle(course.getTitle());
-            courseVo.setCoverImg(course.getCoverImg());
-            courseVo.setPrice(course.getPrice());
-            courseVos.add(courseVo);
-        }
-//       分类查询
-        if (categoryId != 0){
-            List<CourseVo> coursevoList = new ArrayList<>();
-            for (CourseVo courseVo : courseVos) {
-                if (courseVo.getCategoryId()==categoryId){
-                    coursevoList.add(courseVo);
-                }
-            }
-            return coursevoList;
-        }
-        return courseVos;
-    }
+
+
 }
 
 

+ 8 - 0
src/main/java/com/futu/course/es/Service/ESService.java

@@ -0,0 +1,8 @@
+package com.futu.course.es.Service;
+
+import com.futu.course.es.domain.ESCourse;
+import org.springframework.data.mongodb.repository.MongoRepository;
+
+public interface ESService extends MongoRepository<ESCourse,String> {
+
+}

+ 97 - 6
src/main/java/com/futu/course/es/Service/ESCourseService.java → src/main/java/com/futu/course/es/Service/impl/ESCourseService.java

@@ -1,8 +1,9 @@
-package com.futu.course.es.Service;
+package com.futu.course.es.Service.impl;
 
 import com.alibaba.fastjson.JSON;
 import com.futu.course.course.domain.Course;
 import com.futu.course.course.service.impl.CourseServiceImpl;
+import com.futu.course.es.Service.ESService;
 import com.futu.course.es.domain.ESCourse;
 import org.elasticsearch.action.bulk.BulkRequest;
 import org.elasticsearch.action.delete.DeleteRequest;
@@ -39,6 +40,8 @@ public class ESCourseService {
     RestHighLevelClient client;
     @Autowired
     CourseServiceImpl courseService;
+    @Autowired
+    ESService esService;
 
     /**
      * @title: search
@@ -97,7 +100,7 @@ public class ESCourseService {
         // 初始化数据
         for (Course course : list) {
             ESCourse esCourse = new ESCourse();
-            esCourse.setId(course.getId());
+            esCourse.setId(String.valueOf(course.getId()));
             esCourse.setName(course.getTitle());
             esCourse.setCategoryId(Long.valueOf(course.getCategoryId()));
             esCourse.setCoverImg(course.getCoverImg());
@@ -148,9 +151,9 @@ public class ESCourseService {
                     // 处理可能的类型转换问题
                     Object idObj = sourceAsMap.get("id");
                     if (idObj instanceof Integer) {
-                        esCourse.setId(((Integer) idObj).longValue());
+                        esCourse.setId(String.valueOf(((Integer) idObj).longValue()));
                     } else if (idObj instanceof Long) {
-                        esCourse.setId((Long) idObj);
+                        esCourse.setId(String.valueOf((Long) idObj));
                     }
 
                     esCourse.setName((String) sourceAsMap.get("name"));
@@ -191,9 +194,9 @@ public class ESCourseService {
                 // 处理可能的类型转换问题
                 Object idObj = sourceAsMap.get("id");
                 if (idObj instanceof Integer) {
-                    esCourse.setId(((Integer) idObj).longValue());
+                    esCourse.setId(String.valueOf(((Integer) idObj).longValue()));
                 } else if (idObj instanceof Long) {
-                    esCourse.setId((Long) idObj);
+                    esCourse.setId(String.valueOf((Long) idObj));
                 }
 
                 esCourse.setName((String) sourceAsMap.get("name"));
@@ -217,4 +220,92 @@ public class ESCourseService {
         }
         return esCourses;
     }
+    /**
+     * @title: SelCourse
+     * @desc:  搜索并将搜索记录写入到MongoDB中
+     * @params ()
+     * @return: Result
+     * @author: 杨旭朋
+     * @date: 2025/5/8 8:35
+     */
+    public HashSet<ESCourse> SelCourse(String name) throws IOException {
+        // 创建搜索请求
+        SearchRequest searchRequest = new SearchRequest("course");
+        // 创建搜索容器
+        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
+        // 创建布尔查询器
+        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
+                // 创建条件,在条件中添加 match 查询,使用 ik 分词器
+                .must(QueryBuilders.matchQuery("name", name));
+        // 将搜索容器添加搜索条件
+        searchSourceBuilder.query(boolQueryBuilder);
+        // 添加数据为搜索容器
+        searchRequest.source(searchSourceBuilder);
+        // 执行请求,并获取响应
+        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
+        System.out.println(searchRequest);
+        // 返回搜索结果
+        SearchHit[] hits = search.getHits().getHits();
+        HashSet<ESCourse> esCourses = new HashSet<>();
+        for (SearchHit hit : hits) {
+            ESCourse esCourse = new ESCourse();
+            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
+
+            // 处理可能的类型转换问题
+            Object idObj = sourceAsMap.get("id");
+            if (idObj instanceof Integer) {
+                esCourse.setId(String.valueOf(((Integer) idObj).longValue()));
+            } else if (idObj instanceof Long) {
+                esCourse.setId(String.valueOf((Long) idObj));
+            }
+
+            esCourse.setName((String) sourceAsMap.get("name"));
+
+            Object priceObj = sourceAsMap.get("price");
+            if (priceObj instanceof Number) {
+                esCourse.setPrice(BigDecimal.valueOf(((Number) priceObj).doubleValue()));
+            }
+
+            Object categoryIdObj = sourceAsMap.get("category_id");
+            if (categoryIdObj instanceof Integer) {
+                esCourse.setCategoryId(((Integer) categoryIdObj).longValue());
+            } else if (categoryIdObj instanceof Long) {
+                esCourse.setCategoryId((Long) categoryIdObj);
+            }
+
+            esCourse.setCoverImg((String) sourceAsMap.get("cover_img"));
+            esCourses.add(esCourse);
+        }
+        this.SaveMongoDB(name);
+        return esCourses;
+    }
+    /**
+     * @title: SaveMongoDB
+     * @desc:  保存聊天记录到MongoDB中
+     * @params String name
+     * @return: void
+     * @author: 杨旭朋
+     * @date: 2025/5/8 9:14
+     */
+    public void SaveMongoDB(String name){
+        List<ESCourse> all = esService.findAll();
+        int i = 0;
+        for (ESCourse esCourse : all) {
+            if (esCourse.getName().equals(name)){
+                ESCourse byId = esService.findById(esCourse.getId().toString()).get();
+                byId.setCreateTime(new Date());
+                esService.save(byId);
+                i++;
+            }
+        }
+        if (i == 0){
+            ESCourse esCourse = new ESCourse();
+            String string = UUID.randomUUID().toString();
+            esCourse.setId(string);
+            esCourse.setName(name);
+            esCourse.setCreateTime(new Date());
+            esCourse.setUid(1L);
+            esService.save(esCourse);
+        }
+    }
 }

+ 5 - 2
src/main/java/com/futu/course/es/controller/ESCourseController.java

@@ -1,8 +1,7 @@
 package com.futu.course.es.controller;
 
-import com.futu.course.es.Service.ESCourseService;
+import com.futu.course.es.Service.impl.ESCourseService;
 import com.futu.course.es.domain.ESCourse;
-import org.elasticsearch.search.SearchHit;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
@@ -32,4 +31,8 @@ public class ESCourseController {
     public HashSet<ESCourse> CourseList(@RequestParam("categoryId") int categoryId) throws IOException {
         return esCourseService.CourseList(categoryId);
     }
+    @PostMapping("/SelCourse")
+    public HashSet<ESCourse> SelCourse(@RequestParam("name") String name) throws IOException {
+        return esCourseService.SelCourse(name);
+    }
 }

+ 4 - 3
src/main/java/com/futu/course/es/domain/ESCourse.java

@@ -2,26 +2,27 @@ package com.futu.course.es.domain;
 
 import com.fasterxml.jackson.annotation.JsonFormat;
 import org.springframework.data.annotation.Id;
-import org.springframework.data.elasticsearch.annotations.Document;
+
 import org.springframework.data.elasticsearch.annotations.Field;
 import org.springframework.data.elasticsearch.annotations.FieldType;
 import lombok.AllArgsConstructor;
 import lombok.Data;
 import lombok.NoArgsConstructor;
+import org.springframework.data.mongodb.core.mapping.Document;
 
 import java.math.BigDecimal;
 import java.util.Date;
 
 @Data
 // 对 ES 中的 course 进行映射
-@Document(indexName = "course")
+@Document("course")
 @NoArgsConstructor
 @AllArgsConstructor
 public class ESCourse {
     // 用于 Elasticsearch 的主键注解
     @Id
     @Field(type = FieldType.Long)
-    private Long id;
+    private String id;
 
     @Field(name = "name", type = FieldType.Text, analyzer = "ik_max_word")
     private String name;

+ 24 - 0
src/main/java/com/futu/course/minio/config/MinioConfig.java

@@ -0,0 +1,24 @@
+package com.futu.course.minio.config;
+
+import io.minio.MinioClient;
+import lombok.Data;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+
+@Data
+@EnableConfigurationProperties({MinioConfigProperties.class})
+public class MinioConfig {
+
+    @Autowired
+    private MinioConfigProperties minioConfigProperties;
+
+    @Bean
+    public MinioClient minioClient(){
+        return  MinioClient.builder()
+                .endpoint(minioConfigProperties.getEndpoint())
+                .credentials(minioConfigProperties.getAccesskey(), minioConfigProperties.getSecretKey())
+                .build();
+    }
+
+}

+ 21 - 0
src/main/java/com/futu/course/minio/config/MinioConfigProperties.java

@@ -0,0 +1,21 @@
+package com.futu.course.minio.config;
+
+import io.minio.MinioClient;
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+@Data
+@ConfigurationProperties(prefix = "minio")
+public class MinioConfigProperties {
+    //服务器地址
+    /**
+     * minio.endpoint
+     */
+    private String endpoint;
+    private String accesskey;
+    private String secretKey;
+    private String bucketName;
+
+
+
+}

+ 19 - 0
src/main/java/com/futu/course/minio/service/FileService.java

@@ -0,0 +1,19 @@
+package com.futu.course.minio.service;
+
+import io.minio.errors.*;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+
+public interface FileService {
+    //上传
+    public String uploadHtml(MultipartFile multipartFile);
+    public String uploadImage(MultipartFile multipartFile) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException;
+
+
+
+
+}

+ 113 - 0
src/main/java/com/futu/course/minio/service/impl/FileServiceImpl.java

@@ -0,0 +1,113 @@
+package com.futu.course.minio.service.impl;
+
+import com.futu.course.minio.config.MinioConfig;
+import com.futu.course.minio.config.MinioConfigProperties;
+import io.minio.MinioClient;
+import io.minio.ObjectWriteResponse;
+import io.minio.PutObjectArgs;
+import io.minio.errors.*;
+import lombok.SneakyThrows;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Import;
+import org.springframework.stereotype.Service;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.util.UUID;
+
+@Service
+@Import(MinioConfig.class)
+@EnableConfigurationProperties(MinioConfigProperties.class)
+public class FileServiceImpl {
+
+    @Autowired
+    private MinioClient minioClient;
+
+    @Autowired
+    private MinioConfigProperties minioConfigProperties;
+
+
+    @SneakyThrows
+    public String uploadHtml(MultipartFile multipartFile) {
+        InputStream inputStream = multipartFile.getInputStream();
+        if (multipartFile.getSize()<=0 || multipartFile==null){
+            return "文件为空";
+        }
+        String originalFilename = multipartFile.getOriginalFilename();
+        String filename = UUID.randomUUID().toString().replace("-", "") +originalFilename;
+
+        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
+                .bucket(minioConfigProperties.getBucketName())
+                .contentType("text/html")
+                .object(filename)
+                .stream(inputStream, inputStream.available(), -1)
+                .build();
+        ObjectWriteResponse response = minioClient.putObject(putObjectArgs);
+        //获取地址
+        String path = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());
+
+        return path;
+    }
+    @SneakyThrows
+    public String uploadHtml(String fileName, InputStream inputStream){
+        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
+                .bucket(minioConfigProperties.getBucketName())
+                .contentType("text/html")
+                .object(fileName)
+                .stream(inputStream, inputStream.available(), -1)
+                .build();
+
+        ObjectWriteResponse response = minioClient.putObject(putObjectArgs);
+
+        //获取地址
+        String path = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());
+
+        return path;
+    }
+
+    public String uploadImage(MultipartFile multipartFile) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException, IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException {
+        InputStream inputStream = multipartFile.getInputStream();
+
+        if (multipartFile.getSize()<=0 || multipartFile==null){
+            return "文件为空";
+        }
+//        获取原始文件名
+        String originalFilename = multipartFile.getOriginalFilename();
+//        重新生成文件名
+        String filename = UUID.randomUUID().toString().replace("-", "") +originalFilename;
+
+        PutObjectArgs putObjectArgs=PutObjectArgs.builder()
+                .contentType("image/jpg").bucket(minioConfigProperties.getBucketName()).object(filename)
+                .stream(inputStream,inputStream.available(),-1)
+                .build();
+
+        ObjectWriteResponse response = minioClient.putObject(putObjectArgs);
+
+        //获取地址
+        String path = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());
+
+        return path;
+    }
+    public String uploadImage(String fileName, InputStream inputStream) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
+        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
+                .contentType("image/jpg").bucket(minioConfigProperties.getBucketName()).object(fileName)
+                .stream(inputStream, inputStream.available(), -1)
+                .build();
+
+        ObjectWriteResponse response = minioClient.putObject(putObjectArgs);
+
+
+        //获取地址
+        String path = minioClient.getObjectUrl(putObjectArgs.bucket(), putObjectArgs.object());
+
+        return path;
+    }
+
+
+
+
+}

+ 29 - 0
src/main/java/com/futu/course/user/controller/UserController.java

@@ -0,0 +1,29 @@
+package com.futu.course.user.controller;
+
+import com.futu.course.user.service.impl.UserServiceImpl;
+import io.minio.errors.*;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.IOException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+
+/**
+ * @author "杨旭朋"
+ * @ClassName: UserController
+ * @date 2025年05月07日 14:24
+ */
+@RestController
+@RequestMapping("user")
+public class UserController {
+    @Autowired
+    private UserServiceImpl userService;
+    @PostMapping("unload")
+    public String unload(MultipartFile multipartFile,Long uid) throws ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
+        return userService.unload(multipartFile,uid);
+    }
+}

+ 2 - 0
src/main/resources/META-INF/spring.factories

@@ -0,0 +1,2 @@
+org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
+  com.futu.course.minio.service.impl.FileServiceImpl

+ 4 - 0
src/main/resources/application.yml

@@ -1,6 +1,10 @@
 server:
   port: 8003
 spring:
+  data:
+    mongodb:
+      # 在数据库名后添加参数,这里以添加最大连接池大小和最小连接池大小为例
+      uri: mongodb://localhost:27017/course?maxPoolSize=100&minPoolSize=10
   datasource:
     driver-class-name: com.mysql.cj.jdbc.Driver
     url: jdbc:mysql://182.92.251.243:3306/goose?characterEncoding=utf8&serverTimezone=GMT%2B8