• 完成课程的上线下线功能,并更新索引库


    课程的上线

    1.课程管理前端上线
    1.点击某一行数据(@Row-click),把选中的数据保存起来
    2.点击上线按钮,判断是否有选中数据,如果没有抛出异常
    3.发送上线请求到后台,把课程ID作为参数

    行内点击事件:

    @row-click="rowClick"

    前端方法实现:

          //上线的方法
                onLineCourse(){
                    if (!this.row || this.row ===""){
                        this.$message({message:'亲,请选择一门课程!',type:'eror'})
                        return;
                    }
                    this.$http.post("/course/course/onLineCourse/"+this.row.id).then(res=>{
                        console.log(res)
                        console.log("--------------")
                        console.log(res.data)
                        var ajaxResult = res.data;
                        if(ajaxResult.success){
                            this.$message({
                                message: '上线成功!',
                                type: 'success'
                            });
                            this.addFormVisible = false;
                            this.getCourses();
                        }else{
                            this.$message({
                                message: ajaxResult.message,
                                type: 'error'
                            });
                        }
                    });
                },
                //下线的方法
                offLineCourse(){
                    if (!this.row || this.row === ""){
                        this.$message({message:'亲,请选择一门课程!',type:'eror'})
                        return;
                    }
                    this.$http.post("/course/course/offLineCourse/"+this.row.id).then(res=>{
                        var ajaxResult = res.data;
                        if(ajaxResult.success){
                            this.$message({
                                message: '下线成功!',
                                type: 'success'
                            });
                            this.addFormVisible = false;
                            this.getCourses();
                        }else{
                            this.$message({
                                message: ajaxResult.message,
                                type: 'error'
                            });
                        }
                    });
                },
                //列表的点击事件:获得该行信息
                rowClick(row){
                    this.row = row
                }
    2.课程上线后台
    1.从数据库查询上线的课程
    2.判断课程的状态为下线
    3.修改Mysql中课程状态为上线
    4.把课程对象封装成ES的文档对象
    5.调用ES的client把文档对象存储到ES
    3.ES服务的搭建
    hrm-es-parent
        hrm-es-client
        hrm-es-common       //存放ES的doc映射对象
        hrm-es-service-2050
        
    1.搭建hrm-es-service-2050的基础
    2.导入es的依赖 ,yml中 配置es
    3.创建CourseDoc文档映射对象 (hrm-es-common)
    4.创建CourseElasticSearchResposity(hrm-es-service-2050)
    5.创建CourseEsController ,完成  CourseDoc的保存
    6.完成 hrm-es-client 接口的编写
    7.别忘了要初始化索引库
     

    1.hrm-es-common模块:

    依赖:

    <dependencies>
        <!--springboot 对spring data es支持-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
    </dependencies>

    文档映射类:

    /**
     * 针对于  course 表的文档映射
     * indexName:索引库
     * type:类型(表类型)
     *  注意:文档对象中需要哪些列:1.看前端需要哪些列 2.看条件查询有哪些列
     */
    @Document(indexName= "hrm",type = "course")
    public class CourseDoc {
    ​
        //对应文档的Id
        @Id
        private Long id;
    ​
        //课程名称:分词
        @Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
        private String name;
    ​
        //适用人群
        private String users;
    ​
        private String pic;
    ​
        private String courseTypeName;
    ​
        //课程名称
        private String gradeName;
        private String tenantName;
        private String startTime;
        private String endTime;
        private String price;
        ....
        }

    2.hrm-es-service-2050模块(ES服务端):

    引入hrm-es-common的依赖:

            <dependency>
                <groupId>cn.itsource.hrm</groupId>
                <artifactId>hrm-es-common</artifactId>
            </dependency>

    ES服务端配置文件:

    eureka:
      client:
        service-url:
          defaultZone: http://localhost:1010/eureka
      instance:
        prefer-ip-address: true
        instance-id: hrm-es-service
    server:
      port: 2050
    spring:
      application:
        name: hrm-es-service
      data:
        elasticsearch:
          cluster-name: elasticsearch
          cluster-nodes: 127.0.0.1:9300

    配置类:

    @SpringBootApplication  //1.开启自动配置 2.标记这是一个配置类,并把里面的bean放到spring管理 3.开启扫描
    @EnableDiscoveryClient
    public class EsServiceApplication2050 {
        public static void main(String[] args) {
            SpringApplication.run(EsServiceApplication2050.class);
        }
    }

    Es仓库:

    @Repository
    public interface CourseElasticsearchRepository extends ElasticsearchRepository<CourseDoc,Long> {
    }

    ES服务端controller:

    @RestController
    @RequestMapping("/es")
    public class CourseEsController {
        @Autowired
        private CourseElasticsearchRepository courseElasticsearchRepository;
    ​
        //保存方法
        @PostMapping("/save")
        public AjaxResult save(@RequestBody CourseDoc courseDoc){
            courseElasticsearchRepository.save(courseDoc);
            return AjaxResult.me();
        }
    ​
        //删除方法
        @PostMapping("/delete/{id}")
        public AjaxResult delete(@PathVariable Long id){
            courseElasticsearchRepository.deleteById(id);
            return AjaxResult.me();
        }
    }

    3.hrm-es-client模块(Es客户端):

    也会引入hrm-es-common模块的依赖:略

    Feigin接口:

    @FeignClient(value = "hrm-es-service",fallback= EsClientFallBack.class)
    public interface EsClient {
    ​
        //保存方法
        @PostMapping("/es/save")
        AjaxResult save(@RequestBody CourseDoc courseDoc);
    ​
        //删除方法
        @PostMapping("/es/delete/{id}")
        AjaxResult delete(@PathVariable Long id);
    ​
    }

    托底类:

    @Service
    public class EsClientFallBack implements EsClient {
    ​
        @Override
        public AjaxResult save(CourseDoc courseDoc) {
            return AjaxResult.me().setSuccess(false).setMessage("Es服务不可用");
        }
    ​
        @Override
        public AjaxResult delete(Long id) {
            return AjaxResult.me().setSuccess(false).setMessage("Es服务不可用");
        }
    ​
    }

    4.课程模块:hrm-course-service-2020

    引入Es客户端的依赖:

            <dependency>
                <groupId>cn.itsource.hrm</groupId>
                <artifactId>hrm-es-client</artifactId>
            </dependency>

    实现类:CourseServiceImpl类:

    需要使用事务:注解:

    import org.springframework.transaction.annotation.Transactional;
    @Transactional

    上线功能:(注:GlobalException是自定义异常)

        //上线功能
        @Override
        public void onLineCourse(Long id) {
            //1.通过id获得对应的课程
            Course course = baseMapper.selectById(id);
            //2.判断课程的状态,是否为上线状态
            if (course == null ||  Course.STATUS_ONLINE.equals(course.getStatus())){
                throw new GlobalException("亲,该课程已是上线状态");
            }
            
            //3.不是上线状态,更改状态为上线
            course.setStatus(Course.STATUS_ONLINE);
            /*baseMapper.update(course, null);*/
            baseMapper.updateById(course );
    ​
            //4.将查询到的课程信息保存到ES索引库
                //1.创建Srouce的索引库
            CourseDoc courseDoc = new CourseDoc();
                //设置索引库
            courseDoc.setId(course.getId());
    ​
            CourseType courseType = courseTypeMapper.selectById(course.getCourseTypeId());
            courseDoc.setCourseTypeName(courseType.getName());
    ​
            courseDoc.setName(course.getName());
    ​
            courseDoc.setUsers(course.getUsers());
    ​
            courseDoc.setPic(course.getPic());
    ​
            courseDoc.setGradeName(course.getGradeName());
    ​
            courseDoc.setTenantName(course.getTenantName());
    ​
            CourseMarket courseMarket = courseMarketMapper.selectById(course.getId());
            courseDoc.setPrice(courseMarket.getPrice().toString());
    ​
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            courseDoc.setStartTime(simpleDateFormat.format(course.getStartTime()));
            courseDoc.setEndTime(simpleDateFormat.format(course.getEndTime()));
    ​
                //保存到索引库
            AjaxResult ajaxResult = esClient.save(courseDoc);
    ​
            System.out.println(ajaxResult.getMessage());
            //判断是否成功,不成功抛异常,自动回滚
            if (!ajaxResult.isSuccess()){
                throw new GlobalException(ajaxResult.getMessage());
            }
        }

    下线功能:

        //下线功能
        @Override
        public void offLineCourse(Long id) {
            //1.通过id获得对应的课程
            Course course = baseMapper.selectById(id);
            //2.判断课程的状态,是否为下线状态
            if (course == null ||  Course.STATUS_OFFLINE.equals(course.getStatus())){
                throw new GlobalException("亲,该课程已是下线状态");
            }
            //3.不是上线状态,更改状态为上线
            course.setStatus(Course.STATUS_OFFLINE);
            /*baseMapper.update(course, null);*/
            baseMapper.updateById(course);
    ​
            //4.从ES索引库中删除课程
            AjaxResult ajaxResult = esClient.delete(course.getId());
    ​
            //判断是否成功,不成功抛异常,自动回滚
            if (!ajaxResult.isSuccess()){
                throw new GlobalException("亲,该课程已经下线");
            }
        }

    5.注意:别忘了要初始化索引库

        //初始化初始化索引库
        @Test
        public void testEsCourse() throws Exception{
            elasticsearchTemplate.createIndex(CourseDoc.class);
            elasticsearchTemplate.putMapping(CourseDoc.class);
        }
     
  • 相关阅读:
    Unit Vector Compression
    PT, BPT, VCM
    Major Performance Impacts

    SAH Benchmarks Of Natural History Museum Scene
    图标变换图片---轮播切换
    弹出层--弹框
    Git for windows 中文乱码解决方案
    在CentOS上安装Git
    Git 的基本配置
  • 原文地址:https://www.cnblogs.com/htq29study/p/11617346.html
Copyright © 2020-2023  润新知