学成在线笔记五:页面发布及课程管理

页面发布

技术方案

本项目使用MQ实现页面发布的技术方案如下:

学成在线笔记五:页面发布及课程管理_第1张图片

技术方案说明:

  1. 平台包括多个站点,页面归属不同的站点。
  2. 发布一个页面应将该页面发布到所属站点的服务器上。
  3. 每个站点服务部署cms client程序,并与交换机绑定,绑定时指定站点Id为routingKey。指定站点id为routingKey就可以实现cms client只能接收到所属站点的页面发布消息。
  4. 页面发布程序向MQ发布消息时指定页面所属站点Id为routingKey,将该页面发布到它所在服务器上的cms client。

页面发布流程图如下:

学成在线笔记五:页面发布及课程管理_第2张图片

  1. 前端请求cms执行页面发布。
  2. cms执行静态化程序生成html文件。
  3. cms将html文件存储到GridFS中。
  4. cms向MQ发送页面发布消息。
  5. MQ将页面发布消息通知给Cms Client。
  6. Cms Client从GridFS中下载html文件。
  7. Cms Client将html保存到所在服务器指定目录。

页面发布消费方

需求

功能分析:
创建Cms Client工程作为页面发布消费方,将Cms Client部署在多个服务器上,它负责接收到页面发布的消息后从GridFS中下载文件在本地保存。

需求如下:

  1. 将cms Client部署在服务器,配置队列名称和站点ID。
  2. cms Client连接RabbitMQ并监听各自的“页面发布队列”。
  3. cms Client接收页面发布队列的消息。
  4. 根据消息中的页面id从mongodb数据库下载页面到本地。

工程搭建省略

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>xc-framework-parentartifactId>
        <groupId>com.xuechenggroupId>
        <version>1.0-SNAPSHOTversion>
        <relativePath>../xc-framework-parent/pom.xmlrelativePath>
    parent>
    <modelVersion>4.0.0modelVersion>

    <artifactId>xc-service-manage-cms-clientartifactId>
    <dependencies>
        <dependency>
            <groupId>com.xuechenggroupId>
            <artifactId>xc-framework-modelartifactId>
            <version>1.0-SNAPSHOTversion>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-amqpartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-mongodbartifactId>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-ioartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
        dependency>
    dependencies>
project>

配置文件

server:
  port: 31000
spring:
  application:
    name: xc-service-manage-cms-client
  data:
    mongodb:
      database: xc_cms
      host: 127.0.0.1
      port: 27017
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: xcEdu
    password: 123456
    virtualHost: /
xuecheng:
  mq:
    # cms客户端监控的队列名称(不同的客户端监控的队列不能重复)
    queue: queue_cms_postpage_01
    # 此routingKey为门户站点ID
    routingKey: 5a751fab6abb5044e0d19ea1

启动类

package com.xuecheng.cms_manage_client;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@EntityScan(basePackages = "com.xuecheng.framework.domain.cms")
@ComponentScan(basePackages = "com.xuecheng.framework")
@ComponentScan(basePackages = "com.xuecheng.cms_manage_client")
public class ManageCmsClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(ManageCmsClientApplication.class, args);
    }
}

RabbitmqConfig(配置类)

package com.xuecheng.cms_manage_client.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitmqConfig {
    //队列bean的名称
    public static final String QUEUE_CMS_POSTPAGE = "queue_cms_postpage";
    //交换机的名称
    public static final String EX_ROUTING_CMS_POSTPAGE = "ex_routing_cms_postpage";
    //队列的名称
    @Value("${xuecheng.mq.queue}")
    public String queue_cms_postpage_name;
    //routingKey 即站点Id
    @Value("${xuecheng.mq.routingKey}")
    public String routingKey;

    /**
     * 交换机配置使用direct类型
     *
     * @return the exchange
     */
    @Bean(EX_ROUTING_CMS_POSTPAGE)
    public Exchange EXCHANGE_TOPICS_INFORM() {
        return ExchangeBuilder.directExchange(EX_ROUTING_CMS_POSTPAGE).durable(true).build();
    }

    //声明队列
    @Bean(QUEUE_CMS_POSTPAGE)
    public Queue QUEUE_CMS_POSTPAGE() {
        Queue queue = new Queue(queue_cms_postpage_name);
        return queue;
    }

    /**
     * 绑定队列到交换机
     *
     * @param queue    the queue
     * @param exchange the exchange
     * @return the binding
     */
    @Bean
    public Binding BINDING_QUEUE_INFORM_SMS(@Qualifier(QUEUE_CMS_POSTPAGE) Queue queue,
                                            @Qualifier(EX_ROUTING_CMS_POSTPAGE) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(routingKey).noargs();
    }

}

Dao

数据访问代码参考xc-service-manage-cms中的dao,直接复制即可

PageService

package com.xuecheng.cms_manage_client.service;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.xuecheng.cms_manage_client.dao.CmsPageRepository;
import com.xuecheng.cms_manage_client.dao.CmsSiteRepository;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.framework.domain.cms.response.CmsCode;
import com.xuecheng.framework.exception.ExceptionCast;
import com.xuecheng.framework.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.Optional;

@Slf4j
@Service
public class PageService extends BaseService {

    @Autowired
    private GridFSBucket gridFSBucket;

    @Autowired
    private GridFsTemplate gridFsTemplate;

    @Autowired
    private CmsPageRepository cmsPageRepository;

    @Autowired
    private CmsSiteRepository cmsSiteRepository;

    /**
     * 保存指定页面ID的html到服务器
     *
     * @param pageId 页面ID
     */
    public void savePageToServerPath(String pageId) {
        CmsPage cmsPage = null;
        // 查询CmsPage
        Optional<CmsPage> optionalCmsPage = cmsPageRepository.findById(pageId);
        if (!optionalCmsPage.isPresent()) {
            ExceptionCast.cast(CmsCode.CMS_EDITPAGE_NOTEXISTS);
        }
        cmsPage = optionalCmsPage.get();

        // 下载文件
        InputStream inputStream = downloadFileFromMongoDB(cmsPage.getHtmlFileId());
        if (inputStream == null) {
            log.error("[页面发布消费方] 下载页面失败, 流对象为null, fileId = [{}]", cmsPage.getHtmlFileId());
            return ;
        }

        // 写入文件
        FileOutputStream fileOutputStream = null;

        try {
            fileOutputStream = new FileOutputStream(new File(cmsPage.getPagePhysicalPath() + cmsPage.getPageName()));
            IOUtils.copy(inputStream, fileOutputStream);
        } catch (FileNotFoundException e) {
            log.error("[页面发布消费方] 文件未找到, 文件路径 = [{}]", cmsPage.getPagePhysicalPath() + cmsPage.getPageName());
        } catch (IOException e) {
            log.error("[页面发布消费方] 将文件写入服务器失败, 文件路径 = [{}]", cmsPage.getPagePhysicalPath() + cmsPage.getPageName());
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                inputStream.close();
            } catch (IOException e) {
                log.error("[页面发布消费方] 流对象关闭失败, 错误信息 = ", e);
            }

        }
    }

    /**
     * 下载文件
     *
     * @param fileId 文件ID
     * @return 文件内容
     */
    private InputStream downloadFileFromMongoDB(String fileId) {
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
        if (gridFSFile == null) {
            ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_TEMPLATEISNULL);
        }
        //打开下载流对象
        GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建gridFsResource
        GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
        //获取流中的数据
        try {
            return gridFsResource.getInputStream();
        } catch (IOException ignored) { }
        return null;
    }

}

**注意:**我使用的这一版本的数据库中cms_site中没有物理路径这一字段,但是在cms_page中的物理字段使用的是绝对路径,所以我这里直接使用的cms_page中的物理路径。

ConsumerPostPage

编写页面发布消费方代码

package com.xuecheng.cms_manage_client.mq;

import com.alibaba.fastjson.JSON;
import com.xuecheng.cms_manage_client.dao.CmsPageRepository;
import com.xuecheng.cms_manage_client.service.PageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class ConsumerPostPage {

    @Autowired
    private CmsPageRepository cmsPageRepository;

    @Autowired
    private PageService pageService;

    @RabbitListener(queues = {"${xuecheng.mq.queue}"})
    public void postPage(String msg) {
        // 解析消息
        Map map = JSON.parseObject(msg, Map.class);
        log.info("[页面发布消费方] 收到消息, 消息内容为: [{}]", map.toString());

        // 获取pageId
        String pageId = (String) map.get("pageId");
        if (StringUtils.isBlank(pageId)) {
            log.error("[页面发布消费方] 收到的pageId为空");
            return ;
        }
        // 下载页面到服务器
        pageService.savePageToServerPath(pageId);
    }

}

页面发布生产方

需求

管理员通过cms系统发布“页面发布”的消费,cms系统作为页面发布的生产方。

需求如下:

  1. 管理员进入管理界面点击“页面发布”,前端请求cms页面发布接口。
  2. cms页面发布接口执行页面静态化,并将静态化页面存储至GridFS中。
  3. 静态化成功后,向消息队列发送页面发布的消息。
    • 获取页面的信息及页面所属站点ID。
    • 设置消息内容为页面ID。(采用json格式,方便日后扩展)
    • 发送消息给ex_cms_postpage交换机,并将站点ID作为routingKey。

RabbitMQ配置

xc-service-manage-cms工程中,进行下列配置:

  1. 引入依赖(若没有引入amqp的依赖,则需要引入)

    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-amqpartifactId>
    dependency>
    
  2. application.yml中新增Rabbitmq相关配置

    spring:
      rabbitmq:
        host: 127.0.0.1
        port: 5672
        # 此账号是我自行创建的,也可以直接使用默认账号:guest
        username: xcEdu
        password: 123456
        virtualHost: /
    
  3. RabbitMQ配置类

    package com.xuecheng.manage_cms.config;
    
    import org.springframework.amqp.core.Exchange;
    import org.springframework.amqp.core.ExchangeBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class RabbitmqConfig {
    
        //交换机的名称
        public static final String EX_ROUTING_CMS_POSTPAGE = "ex_routing_cms_postpage";
    
        /**
         * 交换机配置使用direct类型
         *
         * @return the exchange
         */
        @Bean(EX_ROUTING_CMS_POSTPAGE)
        public Exchange EXCHANGE_TOPICS_INFORM() {
            return ExchangeBuilder.directExchange(EX_ROUTING_CMS_POSTPAGE).durable(true).build();
        }
    
    }
    

CmsPageControllerApi

CmsPageControllerApi中新增接口定义

    @ApiOperation("页面发布")
    ResponseResult postPage(String pageId);

CmsPageController

    /**
     * 页面发布
     *
     * @param pageId 页面ID
     */
    @Override
    @GetMapping("post/{pageId}")
    public ResponseResult postPage(@PathVariable String pageId) {
        return cmsPageService.postPage(pageId);
    }

CmsPageService

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 页面发布
     *
     * @param pageId 页面ID
     */
    @Transactional
    public CmsPageResult postPage(String pageId) {
        // 执行静态化
        String htmlContent = genHtml(pageId);
        isNullOrEmpty(htmlContent, CmsCode.CMS_GENERATEHTML_HTMLISNULL);

        // 保存页面
        CmsPage cmsPage = saveHtml(pageId, htmlContent);
        
        // 发送消息到MQ
        sendMessage(cmsPage.getPageId());
    }

    /**
     * 发送消息到MQ
     * 
     * @param pageId 页面ID
     */
    private void sendMessage(String pageId) {
        // 查询CmsPage
        CmsPage cmsPage = findByPageId(pageId);
        isNullOrEmpty(cmsPage, CmsCode.CMS_EDITPAGE_NOTEXISTS);
        
        // 构造消息
        JSONObject message = new JSONObject();
        message.put("pageId", pageId);

        // 发送消息
        rabbitTemplate.convertAndSend(RabbitmqConfig.EX_ROUTING_CMS_POSTPAGE, cmsPage.getSiteId(), message.toJSONString());
    }

    /**
     * 保存静态页面
     *
     * @param pageId      页面ID
     * @param htmlContent 页面内容
     */
    private CmsPage saveHtml(String pageId, String htmlContent) {
        // 查询CmsPage
        CmsPage cmsPage = findByPageId(pageId);
        isNullOrEmpty(cmsPage, CmsCode.CMS_EDITPAGE_NOTEXISTS);

        // 删除原有html文件
        String htmlFileId = cmsPage.getHtmlFileId();
        if(StringUtils.isNotEmpty(htmlFileId)){
            gridFsTemplate.delete(Query.query(Criteria.where("_id").is(htmlFileId)));
        }
        
        // 保存生成的html
        InputStream inputStream = IOUtils.toInputStream(htmlContent);
        ObjectId objectId = gridFsTemplate.store(inputStream, cmsPage.getPageName());

        // 保存文件ID到CmsPage
        cmsPage.setHtmlFileId(objectId.toString());
        return cmsPageRepository.save(cmsPage);
    }

前端

用户操作流程:

  • 用户进入cms页面列表。
  • 点击“发布”请求服务端接口,发布页面。
  • 提示“发布成功”,或发布失败。

代码实现如下

  1. cms.js中新增接口定义

    /**
     * 页面发布
     */
    export const postPage = (pageId) => { 
        return http.requestQuickGet(apiUrl + '/cms/page/post/'+ pageId)
    }
    
  2. page_list.vue中新增发布按钮,与页面预览按钮类似

    发布
    
    
  3. page_list.vue的方法区中,新增postPage方法,用于调用页面发布接口

    postPage:function(index, data) {
        this.$confirm('确认发布此页面?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            // 页面发布
            cmsApi.postPage(data.pageId).then(res => {
                // 提示消息
                this.$message({
                    showClose: true,
                    message: res.message,
                    type: 'success'
                })
            })
        })
    }
    

测试

  1. 设置页面信息

    学成在线笔记五:页面发布及课程管理_第3张图片

  2. 点击发布

  3. 查看是否生成文件

    学成在线笔记五:页面发布及课程管理_第4张图片

    OK,文件成功发布并保存。

课程管理

微服务工程导入(省略)

前端工程导入排坑

我这里导入前端工程后,运行报错!!!

错误信息:

Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (64)

???what f**k

然后我去node-sass的github看了下,好像也有蛮多人遇到类似问题的。

https://github.com/microsoft/PartsUnlimited/issues/134

解决方法:

  1. 使用npm update更新版本,需要注意从npm v2.6.1 开始,npm update只更新顶层模块,而不更新依赖的模块,以前版本是递归更新的。如果想取到老版本的效果,要使用下面的命令

    npm --depth 9999 update
    
  2. 重新build一下node-sass

    npm rebuild node-sass
    

然后就可以直接:npm run dev

成功运行。

课程管理实现

分析

  1. 课程列表查询,该功能前端基本上没什么需要修改的地方了,直接写后端的分页查询接口即可。
  2. 课程的新增和编辑(重点),前端已经帮我把课程中的课程分类适用等级以及学习模式的查询调用给我写好了,我们只需要完成响应接口的编写。
    • 课程分类的查询比较简单,在课程微服务中Category表中就能够取到数据,结果只需要封装在CategoryNode中即可。都是已经写好的实体类。
    • 适用等级和学习模式查询,都在mongodb数据库中,也就是之前的CMS相关的数据库中,我们需要在CMS微服务中新增数据字典数据的查询,实体类分别是:SysDictionarySysDictionaryValue
    • 编辑的时候,还需要数据的回显,这就需要完成查询。

数据字典查询实现

  1. DictionaryController

    package com.xuecheng.system.controller;
    
    import com.xuecheng.framework.domain.system.SysDictionary;
    import com.xuecheng.framework.model.response.CommonCode;
    import com.xuecheng.framework.web.BaseController;
    import com.xuecheng.system.service.DictionaryService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("sys/dictionary")
    public class DictionaryController extends BaseController {
    
        @Autowired
        private DictionaryService dictionaryService;
    
        /**
         * 按type获取数据字段值
         *
         * @param type 数据类型
         * @return SysDictionary
         */
        @GetMapping("get/{type}")
        public SysDictionary getDictionaryByType(@PathVariable String type) {
            SysDictionary sysDictionary = dictionaryService.findByType(type);
            isNullOrEmpty(sysDictionary, CommonCode.PARAMS_ERROR);
            return sysDictionary;
        }
    
    }
    
  2. DictionaryService

    package com.xuecheng.system.service;
    
    import com.xuecheng.framework.domain.system.SysDictionary;
    import com.xuecheng.framework.service.BaseService;
    import com.xuecheng.manage_cms.dao.DictionaryRepository;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Slf4j
    @Service
    public class DictionaryService extends BaseService {
    
        @Autowired
        private DictionaryRepository dictionaryRepository;
    
        /**
         * 按type获取数据字段值
         *
         * @param type 数据类型
         * @return SysDictionary
         */
        public SysDictionary findByType(String type) {
            return dictionaryRepository.findByDType(type);
        }
    }
    
  3. DictionaryRepository

    package com.xuecheng.manage_cms.dao;
    
    import com.xuecheng.framework.domain.system.SysDictionary;
    import org.springframework.data.mongodb.repository.MongoRepository;
    
    public interface DictionaryRepository extends MongoRepository<SysDictionary, String> {
    
        SysDictionary findByDType(String type);
    
    }
    

注意:

因为前端已经写好了接口调用而且调用的端口号是cms微服务对应端口号,所以如果不想修改前端的调用端口的话,建议直接将数据字典查询的代码写在cms微服务中。

课程管理实现

  1. CourseController

    package com.xuecheng.manage_course.controller;
    
    import com.xuecheng.api.course.CourseBaseControllerApi;
    import com.xuecheng.framework.domain.course.CourseBase;
    import com.xuecheng.framework.domain.course.request.CourseListRequest;
    import com.xuecheng.framework.domain.course.response.AddCourseResult;
    import com.xuecheng.framework.domain.course.response.CourseBaseResult;
    import com.xuecheng.framework.domain.course.response.CourseCode;
    import com.xuecheng.framework.model.response.CommonCode;
    import com.xuecheng.framework.model.response.QueryResponseResult;
    import com.xuecheng.framework.web.BaseController;
    import com.xuecheng.manage_course.service.CourseBaseService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    @RestController
    @RequestMapping("course/coursebase")
    public class CourseBaseController extends BaseController implements CourseBaseControllerApi {
    
        @Autowired
        private CourseBaseService courseBaseService;
    
    
        @Override
        @GetMapping("list/{page}/{size}")
        public QueryResponseResult findList(@PathVariable int page,
                                            @PathVariable int size,
                                            CourseListRequest queryPageRequest) {
            return courseBaseService.findList(page, size, queryPageRequest);
        }
    
        /**
         * 新增课程基本信息
         *
         * @param courseBase 课程基本信息
         */
        @Override
        @PostMapping("add")
        public AddCourseResult addCourse(@RequestBody CourseBase courseBase) {
            isNullOrEmpty(courseBase, CommonCode.PARAMS_ERROR);
            CourseBase add = courseBaseService.add(courseBase);
            isNullOrEmpty(add, CommonCode.SERVER_ERROR);
            return new AddCourseResult(CommonCode.SUCCESS, add.getId());
        }
    
        /**
         * 编辑课程基本信息
         *
         * @param courseBase 课程基本信息
         */
        @Override
        @PutMapping("edit")
        public AddCourseResult editCourse(@RequestBody CourseBase courseBase) {
            isNullOrEmpty(courseBase, CommonCode.PARAMS_ERROR);
            courseBaseService.edit(courseBase);
            return null;
        }
    
        /**
         * 按课程ID查询课程基本信息
         *
         * @param courseId
         */
        @Override
        @GetMapping("{courseId}")
        public CourseBaseResult findById(@PathVariable String courseId) {
            isNullOrEmpty(courseId, CommonCode.PARAMS_ERROR);
            CourseBase courseBase = courseBaseService.findById(courseId);
            isNullOrEmpty(courseBase, CourseCode.COURSE_NOT_EXIST);
            return CourseBaseResult.SUCCESS(courseBase);
        }
    }
    
  2. CourseBaseService

    package com.xuecheng.manage_course.service;
    
    import com.xuecheng.framework.domain.course.CourseBase;
    import com.xuecheng.framework.domain.course.request.CourseListRequest;
    import com.xuecheng.framework.domain.course.response.CourseCode;
    import com.xuecheng.framework.model.response.CommonCode;
    import com.xuecheng.framework.model.response.QueryResponseResult;
    import com.xuecheng.framework.model.response.QueryResult;
    import com.xuecheng.framework.service.BaseService;
    import com.xuecheng.manage_course.dao.CourseBaseRepository;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Example;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.stereotype.Service;
    
    @Slf4j
    @Service
    public class CourseBaseService extends BaseService {
    
        @Autowired
        private CourseBaseRepository courseBaseRepository;
    
        /**
         * 新增课程基本信息
         *
         * @param courseBase 课程基本信息
         * @return CourseBase
         */
        public CourseBase add(CourseBase courseBase) {
            // 新增
            return courseBaseRepository.save(courseBase);
        }
    
        /**
         * 编辑课程基本信息
         *
         * @param courseBase 课程基本信息
         * @return CourseBase
         */
        public CourseBase edit(CourseBase courseBase) {
            CourseBase _courseBase = findById(courseBase.getId());
            isNullOrEmpty(_courseBase, CourseCode.COURSE_NOT_EXIST);
            // 更新
            _courseBase.setName(courseBase.getName());
            _courseBase.setMt(courseBase.getMt());
            _courseBase.setSt(courseBase.getSt());
            _courseBase.setGrade(courseBase.getGrade());
            _courseBase.setStudymodel(courseBase.getStudymodel());
            _courseBase.setDescription(courseBase.getDescription());
    
            return courseBaseRepository.save(_courseBase);
        }
    
        /**
         * 按ID查询课程基本信息
         *
         * @param courseBaseId 课程ID
         * @return CourseBase
         */
        public CourseBase findById(String courseBaseId) {
            return courseBaseRepository.findById(courseBaseId).orElse(null);
        }
    
        /**
         * 分页查询课程基本信息
         *
         * @param page             当前页码
         * @param size             每页记录数
         * @param queryPageRequest 查询条件
         * @return QueryResponseResult
         */
        public QueryResponseResult findList(int page, int size, CourseListRequest queryPageRequest) {
            if (page < 0) {
                page = 1;
            }
    
            // 页码下标从0开始
            page = page - 1;
            CourseBase params = new CourseBase();
            if (StringUtils.isNotBlank(queryPageRequest.getCompanyId())) {
                params.setCompanyId(queryPageRequest.getCompanyId());
            }
            Example<CourseBase> courseBaseExample = Example.of(params);
    
            // 分页查询
            Page<CourseBase> pageResult = courseBaseRepository.findAll(courseBaseExample, PageRequest.of(page, size));
    
            QueryResult<CourseBase> queryResult = new QueryResult<>();
            queryResult.setTotal(pageResult.getTotalElements());
            queryResult.setList(pageResult.getContent());
    
            return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
        }
    }
    
  3. CourseBaseRepository

    package com.xuecheng.manage_course.dao;
    
    import com.xuecheng.framework.domain.course.CourseBase;
    import org.springframework.data.jpa.repository.JpaRepository;
    
    /**
     * Created by Administrator.
     */
    public interface CourseBaseRepository extends JpaRepository<CourseBase,String> {
    }
    

分类列表查询

  1. CategoryController

    package com.xuecheng.manage_course.controller;
    
    import com.xuecheng.api.course.CategoryControllerApi;
    import com.xuecheng.framework.domain.course.ext.CategoryNode;
    import com.xuecheng.framework.web.BaseController;
    import com.xuecheng.manage_course.service.CategoryService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("category")
    public class CategoryController extends BaseController implements CategoryControllerApi {
    
        @Autowired
        private CategoryService categoryService;
    
        /**
         * 查询分类列表
         *
         * @return CategoryNode
         */
        @Override
        @GetMapping("list")
        public CategoryNode findCategoryList() {
            return categoryService.findCategoryList();
        }
    }
    
  2. CategoryService

    package com.xuecheng.manage_course.service;
    
    import com.xuecheng.framework.domain.course.Category;
    import com.xuecheng.framework.domain.course.ext.CategoryNode;
    import com.xuecheng.manage_course.dao.CategoryRepository;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    import java.util.stream.Collectors;
    
    @Slf4j
    @Service
    public class CategoryService {
    
        @Autowired
        private CategoryRepository categoryRepository;
    
        /**
         * 查询分类列表
         *
         * @return CategoryNode
         */
        public CategoryNode findCategoryList() {
            CategoryNode sourceCategoryNode = buildCategoryNode(categoryRepository.findByParentid("0").get(0));
    
            // 查询第二级分类列表
            List<Category> secondaryCategoryList = categoryRepository.findByParentid(sourceCategoryNode.getId());
            List<CategoryNode> secondaryCategoryNodeList = buildCategoryNodeList(secondaryCategoryList);
    
            sourceCategoryNode.setChildren(secondaryCategoryNodeList);
    
            return sourceCategoryNode;
        }
    
        /**
         * 构造分类节点列表
         *
         * @param categoryList
         * @return List
         */
        private List<CategoryNode> buildCategoryNodeList(List<Category> categoryList) {
            return categoryList.stream().map(secondaryCategory -> {
                CategoryNode categoryNode = buildCategoryNode(secondaryCategory);
                // 查询子节点
                List<Category> children = categoryRepository.findByParentid(categoryNode.getId());
                List<CategoryNode> categoryNodes = buildCategoryNodeList(children);
                if (!categoryNodes.isEmpty()) {
                    categoryNode.setChildren(categoryNodes);
                }
    
                return categoryNode;
            }).collect(Collectors.toList());
        }
    
    
        /**
         * 构造分类节点数据
         *
         * @param category 分类
         * @return CategoryNode
         */
        private CategoryNode buildCategoryNode(Category category) {
            CategoryNode categoryNode = new CategoryNode();
            categoryNode.setId(category.getId());
            categoryNode.setIsleaf(category.getIsleaf());
            categoryNode.setLabel(category.getLabel());
            categoryNode.setName(category.getName());
    
            return categoryNode;
        }
    }
    
  3. CategoryRepository

    package com.xuecheng.manage_course.dao;
    
    import com.xuecheng.framework.domain.course.Category;
    import org.springframework.data.repository.CrudRepository;
    
    import java.util.List;
    
    public interface CategoryRepository extends CrudRepository<Category, String> {
    
        List<Category> findByParentid(String parentId);
    }
    

前端

前端基本没什么需要改动的地方,因为我在课程管理中,使用了自己新建的返回对象CourseBaseResult,所以前端就需要改一点东西,费力不讨好啊,建议各位直接使用CourseBase作为查询的返回值!

学成在线笔记五:页面发布及课程管理_第5张图片

还有就是前端使用element-ui版本,属实有点太低了,很多效果是出不来的,所以我进行了版本更换,我更换到2.10.1之后,课程的新增和编辑页的头部导航菜单出现了样式错误,我修改了一下

学成在线笔记五:页面发布及课程管理_第6张图片

修改之前,是用router-link标签包裹的el-menu-item标签。

基本就这些了。

课程计划

课程计划查询

CoursePlanController

package com.xuecheng.manage_course.controller;

import com.xuecheng.api.course.CoursePlanControllerApi;
import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.manage_course.service.CoursePlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("course/teachplan")
public class CoursePlanController implements CoursePlanControllerApi {

    @Autowired
    private CoursePlanService coursePlanService;

    /**
     * 查询指定课程的课程ID
     *
     * @param courseId 课程ID
     * @return TeachPlanNode
     */
    @Override
    @GetMapping("list/{courseId}")
    public TeachplanNode findList(@PathVariable String courseId) {
        return coursePlanService.findList(courseId);
    }
}

CoursePlanService

package com.xuecheng.manage_course.service;

import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import com.xuecheng.framework.service.BaseService;
import com.xuecheng.manage_course.dao.CoursePlanMapper;
import com.xuecheng.manage_course.dao.CoursePlanRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 课程计划Service
 */
@Slf4j
@Service
public class CoursePlanService extends BaseService {

    @Autowired
    private CoursePlanRepository coursePlanRepository;

    @Autowired
    private CoursePlanMapper coursePlanMapper;


    /**
     * 查询指定课程的课程ID
     *
     * @param courseId 课程ID
     * @return TeachPlanNode
     */
    public TeachplanNode findList(String courseId) {
        return coursePlanMapper.findList(courseId);
    }
}

CoursePlanMapper

package com.xuecheng.manage_course.dao;

import com.xuecheng.framework.domain.course.ext.TeachplanNode;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface CoursePlanMapper {

    /**
     * 查询课程计划列表
     *
     * param courseId 课程ID
     * @return TeachplanNode
     */
    TeachplanNode findList(String courseId);

}

TeachplanMapper.xml



<mapper namespace="com.xuecheng.manage_course.dao.CoursePlanMapper">

    <resultMap id="teachplanMap" type="com.xuecheng.framework.domain.course.ext.TeachplanNode">
        <id column="one_id" property="id" />
        <result column="one_name" property="pname" />
        <collection property="children" ofType="com.xuecheng.framework.domain.course.ext.TeachplanNode">
            <id column="two_id" property="id" />
            <result column="two_name" property="pname" />
            <collection property="children" ofType="com.xuecheng.framework.domain.course.ext.TeachplanNode">
                <id column="three_id" property="id" />
                <result column="three_name" property="pname" />
            collection>
        collection>
    resultMap>


    <select id="findList" parameterType="java.lang.String"
            resultMap="teachplanMap">
        SELECT
            a.id one_id,
            a.pname one_name,
            b.id two_id,
            b.pname two_name,
            c.id three_id,
            c.pname three_name
        FROM
            teachplan a LEFT JOIN teachplan b
            ON a.id = b.parentid
            LEFT JOIN teachplan c
            ON b.id = c.parentid
        WHERE a.parentid = '0'
            <if test="_parameter!=null and _parameter!=''">
                and a.courseid=#{courseId}
            if>

        ORDER BY a.orderby,
            b.orderby,
            c.orderby
    select>

mapper>

测试

学成在线笔记五:页面发布及课程管理_第7张图片

排坑

调用mapper方法的时候报错:

Invalid bound statement (not found): com.xuecheng.manage_course.dao.CoursePlanMapper.findList

原因是mybatis没有正确的加载到mapper.xml文件,在application.yml中加入下方配置

mybatis:
  mapper-locations: classpath:com/xuecheng/manage_course/dao/*Mapper.xml

添加课程计划

CoursePlanController

    /**
     * 新增课程计划
     *
     * @param teachplan 课程计划
     * @return ResponseResult
     */
    @Override
    @PostMapping("add")
    public ResponseResult add(@RequestBody Teachplan teachplan) {
        if (teachplan == null || StringUtils.isBlank(teachplan.getCourseid())) {
            return new ResponseResult(CommonCode.PARAMS_ERROR);
        }
        // 新增
        Teachplan add = coursePlanService.add(teachplan);
        isNullOrEmpty(add, CourseCode.COURSE_PLAN_ADD_ERROR);
        return ResponseResult.SUCCESS();
    }

CoursePlanService

    /**
     * 新增课程计划
     *
     * @param teachplan 课程计划
     * @return Teachplan
     */
    public Teachplan add(Teachplan teachplan) {
        Teachplan root = getTeachplanRoot(teachplan.getCourseid());

        // 设置父ID
        if (StringUtils.isBlank(teachplan.getParentid())) {
            teachplan.setParentid(root.getId());
        }
        // 设置节点级别
        if (root.getId().equals(teachplan.getParentid())) {// 第二级别
            teachplan.setGrade("2");
        } else {// 第三级别
            teachplan.setGrade("3");
        }

        return coursePlanRepository.save(teachplan);
    }

    /**
     * 查询指定课程的课程计划根节点
     *
     * @param courseId 课程计划
     * @return Teachplan
     */
    public Teachplan getTeachplanRoot(String courseId) {
        // 查询课程基本信息
        Optional<CourseBase> courseBase = courseBaseRepository.findById(courseId);
        if (!courseBase.isPresent()) {
            ExceptionCast.cast(CourseCode.COURSE_NOT_EXIST);
        }

        // 查询根节点下的所有二级节点
        List<Teachplan> secondaryTeachplanList = coursePlanRepository.findByCourseidAndParentid(courseBase.get().getId(), "0");
        if (secondaryTeachplanList == null || secondaryTeachplanList.isEmpty()) {// 若不存在根节点
            // 创建根节点
            Teachplan root = new Teachplan();
            root.setCourseid(courseBase.get().getId());
            root.setPname(courseBase.get().getName());
            root.setParentid("0");// 根节点
            root.setGrade("1");// 1级菜单
            root.setStatus("0");// 未发布

            coursePlanRepository.save(root);
            return root;
        }

        return secondaryTeachplanList.get(0);
    }

CoursePlanRepository

package com.xuecheng.manage_course.dao;

import com.xuecheng.framework.domain.course.Teachplan;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

public interface CoursePlanRepository extends CrudRepository<Teachplan, String> {

    /**
     * 查询课程指定父ID的所有节点列表
     *
     * @param courseId 课程ID
     * @param parentId 父ID
     * @return List
     */
    List<Teachplan> findByCourseidAndParentid(String courseId, String parentId);
}

前端

修改保存成功后,关闭表单输入窗口,修改course_pan.vue中的addTeachplan方法

addTeachplan(){
    //校验表单
    this.$refs.teachplanForm.validate((valid) => {
        if (valid) {
            //调用api方法
            //将课程id设置到teachplanActive
            this.teachplanActive.courseid = this.courseid
            courseApi.addTeachplan(this.teachplanActive).then(res=>{
                if(res.success){
                    this.$message({
                        showClose: true,
                        message: res.message,
                        type: 'success'
                    })
                    //关闭课程计划信息录入窗口
                    this.teachplayFormVisible = false
                    //刷新树
                    this.findTeachplan()
                }else{
                    this.$message.error(res.message)
                }
            })
        }
    })
}

编辑/删除课程计划

后端

  1. CoursePlanController

        /**
         * 编辑课程计划
         *
         * @param teachplan 课程计划
         * @return ResponseResult
         */
        @Override
        @PutMapping("edit")
        public ResponseResult edit(@RequestBody Teachplan teachplan) {
            if (teachplan == null
                    || StringUtils.isBlank(teachplan.getCourseid())
                    || StringUtils.isBlank(teachplan.getId())) {
                return new ResponseResult(CommonCode.PARAMS_ERROR);
            }
            // 编辑
            Teachplan edit = coursePlanService.edit(teachplan);
            isNullOrEmpty(edit, CourseCode.COURSE_PLAN_ADD_ERROR);
            return ResponseResult.SUCCESS();
        }
    
        /**
         * 删除课程计划
         *
         * @param teachplanId 课程计划ID
         * @return ResponseResult
         */
        @Override
        @DeleteMapping("{teachplanId}")
        public ResponseResult delete(@PathVariable String teachplanId) {
            coursePlanService.deleteById(teachplanId);
            return ResponseResult.SUCCESS();
        }
    
  2. CoursePlanService

        /**
         * 编辑课程计划
         *
         * @param teachplan 课程计划
         * @return Teachplan
         */
        public Teachplan edit(Teachplan teachplan) {
            Optional<Teachplan> optionalTeachplan = coursePlanRepository.findById(teachplan.getId());
            if (!optionalTeachplan.isPresent()) {
                ExceptionCast.cast(CourseCode.COURSE_NOT_EXIST);
            }
            Teachplan _teachplan = optionalTeachplan.get();
            _teachplan.setGrade(teachplan.getGrade());
            _teachplan.setPname(teachplan.getPname());
            _teachplan.setCourseid(teachplan.getCourseid());
            _teachplan.setDescription(teachplan.getDescription());
            _teachplan.setOrderby(teachplan.getOrderby());
            _teachplan.setStatus(teachplan.getStatus());
            _teachplan.setTimelength(teachplan.getTimelength());
    
            Teachplan root = getTeachplanRoot(teachplan.getCourseid());
    
            // 设置父ID
            if (StringUtils.isBlank(teachplan.getParentid())) {
                _teachplan.setParentid(root.getId());
            }
    
            return coursePlanRepository.save(_teachplan);
        }
    
    	/**
         * 查询指定ID的课程计划
         *
         * @param teachplanId 课程计划ID
         * @return Teachplan
         */
        public Teachplan findById(String teachplanId) {
            Optional<Teachplan> optionalTeachplan = coursePlanRepository.findById(teachplanId);
            if (!optionalTeachplan.isPresent()) {
                ExceptionCast.cast(CourseCode.COURSE_NOT_EXIST);
            }
            return optionalTeachplan.get();
        }
    
        /**
         * 删除指定ID的课程计划
         *
         * @param teachplanId 课程计划ID
         */
        public void deleteById(String teachplanId) {
            coursePlanRepository.deleteById(teachplanId);
        }
    

前端

  1. 新增API定义,修改course.js

    /*查询课程计划*/
    export const findTeachplanById = teachplanById => {
      return http.requestQuickGet(apiUrl+'/course/teachplan/'+teachplanById)
    }
    /*编辑课程计划*/
    export const editTeachplan = teachplah => {
      return http.requestPut(apiUrl+'/course/teachplan/edit',teachplah)
    }
    /*删除课程计划*/
    export const deleteTeachplan = teachplahId => {
      return http.requestDelete(apiUrl+'/course/teachplan/' + teachplahId)
    }
    
  2. 页面修改,修改内容主要为

    • 点击修改按钮,弹出修改框并回显数据,提交API调用
    • 点击删除按钮,弹出确认框,确认后API调用
    	edit(data){
            // 查询
            courseApi.findTeachplanById(data.id).then(res => {
              this.teachplanActive = res
              if (res.grade === '2') {
                this.teachplanActive.parentid = ''
              }
              this.teachplayFormVisible = true
            })
            //校验表单
            this.$refs.teachplanForm.validate((valid) => {
                if (valid) {
                    //调用api方法
                  //将课程id设置到teachplanActive
                  this.teachplanActive.courseid = this.courseid
                  courseApi.editTeachplan(this.teachplanActive).then(res=>{
                    if(res.success){
                        this.$message({
                            showClose: true,
                            message: res.message,
                            type: 'success'
                        })
                        this.teachplayFormVisible = false
                        //刷新树
                        this.findTeachplan()
                    }else{
                      this.$message.error(res.message)
                    }
    
                  })
                }
            })
          },
          remove(node, data) {
            // 执行删除
            this.$confirm('确认删除该课程计划?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }).then(() => {
                  // 删除
                  courseApi.deleteTeachplan(data.id).then(res => {
                    // 提示消息
                    this.$message({
                      showClose: true,
                      message: res.message,
                      type: 'success'
                    })
    				//刷新树
                    this.findTeachplan()
                  })
                  
              })
    
          }
    

    注意:

    由于新增和编辑用的同一个表单按钮,所以要做判断,若ID为空时调用新增,否则调用编辑

    // 将按钮调用改为save方法
    <el-button type="primary" v-on:click="save">提交</el-button>
    
    save() {
        if (this.teachplanActive.id) {
            this.edit(this.teachplanActive)
        } else {
            this.addTeachplan()
        }
    }
    

因为我没看课程目录,后一天的内容居然是课程管理的实战。。我在这一笔记里面就自己把课程管理的实战给做了,但是缺少课程营销相关的内容,我就不做了,懒得做(懒人就是我)

你可能感兴趣的:(学成在线,学成在线,在线教育,学成在线笔记,学成在线实战)