赞
踩
项目导读
大家好,我是HuiCode,此遍文章呢故名思意就是硅谷课堂的一个小总结,当然官网提供的文档会更加全面,我只是把我认为学到的技术汇总以下,方便以后观看,复习,大家要是有兴趣的话,也可以看一看,若是对你有所帮助希望可以点赞,关注,支持一下,谢谢
**ggkt_parent:**硅谷课堂根目录(父工程),管理多个子模块:
common:公共模块父节点
service_utils:service服务的base包,包含service服务的公共配置类,所有service模块依赖于它
model:实体类相关模块
server-gateway:服务网关
service:api接口服务父节点
service_activity:优惠券api接口服务
service_order:订单api接口服务
service_user:用户api接口服务
service_vod:点播课程 api接口服务
service_wechat:公众号api接口服务
service-client:feign服务调用父节点
service-activity-client:优惠券api接口
service-user-client:用户api接口
service-course-client:课程api接口
<modules> <module>model</module> <module>service</module> <module>common</module> <module>service_gateway</module> <module>service_client</module> </modules> <!-- springboot版本--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.huicode</groupId> <artifactId>ggkt_parent</artifactId> <version>0.0.1-SNAPSHOT</version> <name>ggkt_parent</name> <description>Demo project for Spring Boot</description> <properties> <skipTests>true</skipTests> <java.version>1.8</java.version> <cloud.version>Hoxton.RELEASE</cloud.version> <alibaba.version>2.2.0.RELEASE</alibaba.version> <mybatis-plus.version>3.4.1</mybatis-plus.version> <mysql.version>5.1.46</mysql.version> <swagger.version>2.9.2</swagger.version> <jwt.version>0.7.0</jwt.version> <fastjson.version>1.2.29</fastjson.version> <httpclient.version>4.5.1</httpclient.version> <easyexcel.version>2.2.0-beta2</easyexcel.version> <jodatime.version>2.10.1</jodatime.version> <jwt.version>0.7.0</jwt.version> <xxl-job.version>2.3.0</xxl-job.version> </properties> <!--配置dependencyManagement锁定依赖的版本--> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <!--mybatis-plus 持久层--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis-plus.version}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>2.0.8</version> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>${jwt.version}</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>${httpclient.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>${easyexcel.version}</version> </dependency> <!--日期时间工具--> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>${jodatime.version}</version> </dependency> <!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger.version}</version> </dependency> <!--swagger ui--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
注意加上注解@EnableSwagger2,@EnableSwagger2
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket webApiConfig(){ return new Docket(DocumentationType.SWAGGER_2) .groupName("ggkt") .apiInfo(webApiInfo()) .select() //只显示api路径下的页面 //.paths(Predicates.and(PathSelectors.regex("/api/.*"))) .build(); } private ApiInfo webApiInfo(){ return new ApiInfoBuilder() .title("网站-API文档") .description("本文档描述了网站微服务接口定义") .version("1.0") .contact(new Contact("atguigu", "http://atguigu.com", "atguigu.com")) .build(); } }
添加上注解@ComponentScan(“com.huicode”)用于扫描配置类
@SpringBootApplication
@ComponentScan("com.huicode")
public class ServiceVodApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceVodApplication.class, args);
}
}
定义在类上:@Api
定义在方法上:@ApiOperation
定义在参数上:@ApiParam
浏览器输入固定地址 http://localhost:8301/swagger-ui.html
此处的8301是项目端口号
打开腾讯云官网,进行以下操作
1.1、开通“对象存储COS”服务
1.2、创建Bucket
1.3、创建API秘钥
1.4、快速入门
参考文档:https://cloud.tencent.com/document/product/436/10199
2.1引入依赖
<dependencies>
<!-- 腾讯云COS依赖 -->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.54</version>
</dependency>
<!-- 日期工具栏依赖 -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>
2.2、配置application.properties
添加如下内容:
spring.servlet.multipart.max-file-size=1024MB
spring.servlet.multipart.max-request-size=1024MB
#不同的服务器,地址不同
tencent.cos.file.region=ap-beijing
tencent.cos.file.secretid=你的id
tencent.cos.file.secretkey=你的key
#bucket可以在控制台创建,也可以使用java代码创建
tencent.cos.file.bucketname=你的bucketName
2.3、创建工具类
/** * 常量类,读取配置文件application.properties中的配置 */ @Component public class ConstantPropertiesUtil implements InitializingBean { @Value("${tencent.cos.file.region}") private String region; @Value("${tencent.cos.file.secretid}") private String secretId; @Value("${tencent.cos.file.secretkey}") private String secretKey; @Value("${tencent.cos.file.bucketname}") private String bucketName; public static String END_POINT; public static String ACCESS_KEY_ID; public static String ACCESS_KEY_SECRET; public static String BUCKET_NAME; @Override public void afterPropertiesSet() throws Exception { END_POINT = region; ACCESS_KEY_ID = secretId; ACCESS_KEY_SECRET = secretKey; BUCKET_NAME = bucketName; } }
2.4 编写service,serviceImpl,controller
service
public interface FileService {
//文件上传
String upload(MultipartFile file);
}
serviceImpl
@Service public class FileServiceImpl implements FileService { @Override public String upload(MultipartFile file) { // Endpoint以杭州为例,其它Region请按实际情况填写。 String endpoint = ConstantPropertiesUtil.END_POINT;//获取地域节点 String bucketName = ConstantPropertiesUtil.BUCKET_NAME; //获取桶的姓名 // 1 初始化用户身份信息(secretId, secretKey)。 String secretId = ConstantPropertiesUtil.ACCESS_KEY_ID; String secretKey = ConstantPropertiesUtil.ACCESS_KEY_SECRET; COSCredentials cred = new BasicCOSCredentials(secretId, secretKey); // 2 设置 bucket 的地域 // clientConfig 中包含了设置 region, https(默认 http),超时, 代理等 set 方法 Region region = new Region(ConstantPropertiesUtil.END_POINT);//地域jie'dian ClientConfig clientConfig = new ClientConfig(region); // 这里建议设置使用 https 协议 // 从 5.6.54 版本开始,默认使用了 https clientConfig.setHttpProtocol(HttpProtocol.https); // 3 生成 cos 客户端。 COSClient cosClient = new COSClient(cred, clientConfig); try{ // 指定要上传的文件 InputStream inputStream = file.getInputStream(); // 指定文件将要存放的存储桶 // 指定文件上传到 COS 上的路径,即对象键。例如对象键为folder/picture.jpg,则表示将文件 picture.jpg 上传到 folder 路径下 String key = UUID.randomUUID().toString().replaceAll("-","")+ file.getOriginalFilename(); String dateUrl = new DateTime().toString("yyyy/MM/dd"); key = dateUrl+"/"+key; ObjectMetadata objectMetadata = new ObjectMetadata(); PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream,objectMetadata); PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); System.out.println(JSON.toJSONString(putObjectResult)); //https://ggkt-atguigu-1310644373.cos.ap-beijing.myqcloud.com/01.jpg String url = "https://"+bucketName+"."+"cos"+"."+endpoint+".myqcloud.com"+"/"+key; return url; } catch (Exception clientException) { clientException.printStackTrace(); return null; } } }
controller
@Api(tags = "文件上传接口") @RestController @RequestMapping("/admin/vod/file") public class FileUploadController { @Autowired private FileService fileService; /** * 文件上传 */ @ApiOperation(value = "文件上传") @PostMapping("upload") public Result upload( @ApiParam(name = "file", value = "文件", required = true) @RequestParam("file") MultipartFile file) { String uploadUrl = fileService.upload(file); return Result.ok(uploadUrl).message("文件上传成功"); } }
1.引入相关依赖
(1)在service_vod模块引入
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>vod_api</artifactId>
<version>2.1.4</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
2、编写Controller
**(1)上传视频集成方案:**https://cloud.tencent.com/document/product/266/10276
(2)删除视频
可在线生成代码:
地址:https://console.cloud.tencent.com/api/explorer?Product=vod&Version=2018-07-17&Action=DescribeMediaInfos&SignVersion=
@Api(tags = "腾讯云点播") @RestController @RequestMapping("/admin/vod") @CrossOrigin public class VodController { @Autowired private VodService vodService; //上传视频 @PostMapping("upload") public Result uploadVideo( @ApiParam(name = "file", value = "文件", required = true) @RequestParam("file") MultipartFile file) throws IOException { InputStream inputStream = file.getInputStream(); String originalFilename = file.getOriginalFilename(); String videoId = vodService.uploadVideo(inputStream, originalFilename); return Result.ok(videoId); } //删除视频 @DeleteMapping("remove/{videoSourceId}") public Result removeVideo( @PathVariable String videoSourceId) { vodService.removeVideo(videoSourceId); return Result.ok(); } }
3.编写Service
(1)VodService定义方法
public interface VodService {
//上传视频
String uploadVideo(InputStream inputStream, String originalFilename);
//删除视频
void removeVideo(String videoSourceId);
}
(2)VodServiceImpl实现方法
@Service public class VodServiceImpl implements VodService { //上传视频 @Override public String uploadVideo(InputStream inputStream, String originalFilename) { try { VodUploadClient client = new VodUploadClient(ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_KEY_SECRET); VodUploadRequest request = new VodUploadRequest(); //视频本地地址 request.setMediaFilePath("D:\\001.mp4"); //指定任务流 request.setProcedure("LongVideoPreset"); //调用上传方法,传入接入点地域及上传请求。 VodUploadResponse response = client.upload("ap-guangzhou", request); //返回文件id保存到业务表,用于控制视频播放 String fileId = response.getFileId(); System.out.println("Upload FileId = {}"+response.getFileId()); return fileId; } catch (Exception e) { System.out.println(e.toString()); } return null; } //删除视频 @Override public void removeVideo(String videoSourceId) { try{ // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密 Credential cred = new Credential(ConstantPropertiesUtil.ACCESS_KEY_ID, ConstantPropertiesUtil.ACCESS_KEY_SECRET); // 实例化要请求产品的client对象,clientProfile是可选的 VodClient client = new VodClient(cred, ""); // 实例化一个请求对象,每个接口都会对应一个request对象 DeleteMediaRequest req = new DeleteMediaRequest(); req.setFileId(videoSourceId); // 返回的resp是一个DeleteMediaResponse的实例,与请求对象对应 DeleteMediaResponse resp = client.DeleteMedia(req); // 输出json格式的字符串回包 System.out.println(DeleteMediaResponse.toJsonString(resp)); } catch (TencentCloudSDKException e) { System.out.println(e.toString()); } } }
课程分类采用树形展示,我们使用“树形数据与懒加载”的方式展现数据列表,因此需要提供的接口如下:根据上级id获取下级数据,参考element-ui文档:https://element.eleme.cn/#/zh-CN/component/table,页面搜索:树形数据与懒加载
我们主要看serviceImpl类中的逻辑就好
@Service public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService { //查询下一层课程分类 @Override public List<Subject> selectList(Long id) { QueryWrapper<Subject> wrapper = new QueryWrapper<>(); wrapper.eq("parent_id",id); List<Subject> subjectList = baseMapper.selectList(wrapper); //向list集合每个Subject对象中设置hasChildren for (Subject subject:subjectList) { Long subjectId = subject.getId(); boolean isChild = this.isChildren(subjectId); subject.setHasChildren(isChild); } return subjectList; } //判断id下面是否有子节点 private boolean isChildren(Long id) { QueryWrapper<Subject> wrapper = new QueryWrapper<>(); wrapper.eq("parent_id",id); Integer count = baseMapper.selectCount(wrapper); return count>0; } }
EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单、节省内存著称。EasyExcel能大大减少占用内存的主要原因是在解析Excel时没有将文件数据一次性全部加载到内存中,而是从磁盘上一行行读取数据,逐个解析。
(1)pom中引入xml相关依赖
<dependencies>
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
(2)创建实体类
设置表头和添加的数据字段
注意加上注解@ExcelProperty
@Data
public class Stu {
//设置表头名称
@ExcelProperty("学生编号")
private int sno;
//设置表头名称
@ExcelProperty("学生姓名")
private String sname;
}
(3)实现写操作
创建方法循环设置要添加到Excel的数据
//循环设置要添加的数据,最终封装到list集合中
private static List<Stu> data() {
List<Stu> list = new ArrayList<Stu>();
for (int i = 0; i < 10; i++) {
Stu data = new Stu();
data.setSno(i);
data.setSname("张三"+i);
list.add(data);
}
return list;
}
实现最终的添加操作
public static void main(String[] args) throws Exception {
// 写法1
String fileName = "F:\\11.xlsx";
// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
// 如果这里想使用03 则 传入excelType参数即可
EasyExcel.write(fileName, Stu.class)
.sheet("写入方法")
.doWrite(data());
}
(1)创建实体类
@Data
public class Stu {
//设置表头名称
//设置列对应的属性
@ExcelProperty(value = "学生编号",index = 0)//从第1列开始
private int sno;
//设置表头名称
//设置列对应的属性
@ExcelProperty(value = "学生姓名",index = 1)//从第2列开始
private String sname;
}
(2)创建读取操作的监听器
public class ExcelListener extends AnalysisEventListener<Stu> { //创建list集合封装最终的数据 List<Stu> list = new ArrayList<Stu>(); //一行一行去读取excle内容 //这是从第二行开始读取的 @Override public void invoke(Stu user, AnalysisContext analysisContext) { System.out.println("***"+user); list.add(user); } //读取excel表头信息 @Override public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) { System.out.println("表头信息:"+headMap); } //读取完成后执行 @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { } }
(3)调用实现最终的读取
public static void main(String[] args) throws Exception {
String fileName = "F:\\11.xlsx";
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭
EasyExcel.read(fileName, Stu.class, new ExcelListener())
.sheet() //默认读第一个sheet
.doRead();
}
1、查看model实体类
@Data
public class SubjectEeVo {
@ExcelProperty(value = "id" ,index = 0)
private Long id;
@ExcelProperty(value = "课程分类名称" ,index = 1)
private String title;
@ExcelProperty(value = "上级id" ,index = 2)
private Long parentId;
@ExcelProperty(value = "排序" ,index = 3)
private Integer sort;
}
2.编写服务
SubjectService
/**
* 导出
* @param response
*/
void exportData(HttpServletResponse response);
SubjectServiceImpl
//课程分类导出 @Override public void exportData(HttpServletResponse response) { try { response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系 String fileName = URLEncoder.encode("课程分类", "UTF-8"); response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx"); List<Subject> dictList = baseMapper.selectList(null); List<SubjectEeVo> dictVoList = new ArrayList<>(dictList.size()); for(Subject dict : dictList) { SubjectEeVo dictVo = new SubjectEeVo(); BeanUtils.copyProperties(dict,dictVo); dictVoList.add(dictVo); } EasyExcel.write(response.getOutputStream(), SubjectEeVo.class).sheet("课程分类").doWrite(dictVoList); } catch (IOException e) { e.printStackTrace(); } }
controller中
@ApiOperation(value="导出")
@GetMapping(value = "/exportData")
public void exportData(HttpServletResponse response) {
subjectService.exportData(response);
}
前端:
1)list.vue页面添加导出按钮**
<div class="el-toolbar">
<div class="el-toolbar-body" style="justify-content: flex-start;">
<el-button type="text" @click="exportData"><i class="fa fa-plus"/> 导出</el-button>
</div>
</div>
(2)编写调用方法
exportData() {
window.open("http://localhost:8301/admin/vod/subject/exportData")
},
导入即为读操作,需要用到监听器
1、创建读取监听器
@Component public class SubjectListener extends AnalysisEventListener<SubjectEeVo> { @Autowired private SubjectMapper dictMapper; //一行一行读取 @Override public void invoke(SubjectEeVo subjectEeVo, AnalysisContext analysisContext) { //调用方法添加数据库 Subject subject = new Subject(); BeanUtils.copyProperties(subjectEeVo,subject); dictMapper.insert(subject); } @Override public void doAfterAllAnalysed(AnalysisContext analysisContext) { } }
2、添加controller方法
@ApiOperation(value = "导入")
@PostMapping("importData")
public Result importData(MultipartFile file) {
subjectService.importDictData(file);
return Result.ok();
}
3、添加service方法
@Autowired
private SubjectListener subjectListener;
//导入
@Override
public void importData(MultipartFile file) {
try {
EasyExcel.read(file.getInputStream(),
SubjectEeVo.class,subjectListener)
.sheet().doRead();
} catch (IOException e) {
e.printStackTrace();
}
}
4、数据字典导入前端
(1)在list.vue页面添加导入按钮
<el-button type="text" @click="importData"><i class="fa fa-plus"/> 导入</el-button>
(2)添加导入弹出层
<el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px"> <el-form label-position="right" label-width="170px"> <el-form-item label="文件"> <el-upload :multiple="false" :on-success="onUploadSuccess" :action="'http://localhost:8333/admin/vod/subject/importData'" class="upload-demo"> <el-button size="small" type="primary">点击上传</el-button> <div slot="tip" class="el-upload__tip">只能上传xls文件,且不超过500kb</div> </el-upload> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="dialogImportVisible = false">取消</el-button> </div> </el-dialog>
项目中写SQL语句的比较少,这里拿出一个讲解一下,写SQL语句的注意点
1.编写CourseMapper.xml
id,为你在mapper接口中定义的方法名
<select id="selectCoursePublishVoById" resultType="com.huicode.ggkt.vo.vod.CoursePublishVo"> SELECT c.id, c.title, c.cover, c.lesson_num AS lessonNum, c.price, t.name AS teacherName, s1.title AS subjectParentTitle, s2.title AS subjectTitle FROM course c LEFT OUTER JOIN teacher t ON c.teacher_id=t.id LEFT OUTER JOIN `subject` s1 ON c.subject_parent_id=s1.id LEFT OUTER JOIN `subject` s2 ON c.subject_id=s2.id WHERE c.id=#{id} </select>
个人总结的写SQL的技巧
select 1(字段) from 2(表名)
3(如:左连接) join 4(表名)
on 5(条件)
2.添加配置
为了是xml文件的SQL语句被搜索到
(1)application.properties添加
注意路径名,写项目XML文件的路径
mybatis-plus.mapper-locations=classpath:com/huicode/ggkt/vod/mapper/xml/*.xml
(2)service模块pom.xml添加
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.yml</include> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.yml</include> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
1…编写Controller
VideoVisitorController添加
@Api(value = "VideoVisitor管理", tags = "VideoVisitor管理") @RestController @RequestMapping(value="/admin/vod/videoVisitor") @CrossOrigin public class VideoVisitorController { @Autowired private VideoVisitorService videoVisitorService; @ApiOperation("显示统计数据") @GetMapping("findCount/{courseId}/{startDate}/{endDate}") public Result showChart( @ApiParam("开始时间") @PathVariable Long courseId, @ApiParam("开始时间") @PathVariable String startDate, @ApiParam("结束时间") @PathVariable String endDate){ Map<String, Object> map = videoVisitorService.findCount(courseId, startDate, endDate); return Result.ok(map); } }
2.编写Service和实现
VideoVisitorService和VideoVisitorServiceImpl
@Service public class VideoVisitorServiceImpl extends ServiceImpl<VideoVisitorMapper, VideoVisitor> implements VideoVisitorService { //课程统计的接口 @Override public Map<String, Object> findCount(Long courseId, String startDate, String endDate) { //调用mapper的方法 List<VideoVisitorCountVo> videoVisitorVoList = baseMapper.findCount(courseId,startDate,endDate); //创建map集合 Map<String, Object> map = new HashMap<>(); //创建两个list集合,一个代表所有日期,一个代表日期对应数量 //封装数据 代表所有日期 List<String> dateList = videoVisitorVoList.stream().map(VideoVisitorCountVo::getJoinTime). collect(Collectors.toList()); //代表日期对应数量 List<Integer> countList = videoVisitorVoList.stream().map(VideoVisitorCountVo::getUserCount) .collect(Collectors.toList()); //放到map集合 map.put("xData", dateList); map.put("yData", countList); return map; } }
3.编写Mapper
(1)VideoVisitorMapper
public interface VideoVisitorMapper extends BaseMapper<VideoVisitor> {
显示统计数据
List<VideoVisitorCountVo> findCount(Long courseId, String startDate, String endDate);
}
(2)VideoVisitorMapper.xml文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.atguigu.ggkt.vod.mapper.VideoVisitorMapper"> <select id="findCount" resultType="com.atguigu.ggkt.vo.vod.VideoVisitorCountVo"> SELECT DATE(join_time) AS joinTime, COUNT(*) AS userCount FROM video_visitor <where> <if test="startDate != null and startDate != ''"> AND DATE(join_time) >= #{startDate} </if> <if test="endDate != null and endDate != ''"> AND DATE(join_time) <= #{endDate} </if> and course_id=#{courseId} </where> GROUP BY DATE(join_time) ORDER BY DATE(join_time) </select> </mapper>
前端
1.安装ECharts组件
ECharts是百度的一个项目,后来百度把Echart捐给apache,用于图表展示,提供了常规的折线图、柱状图、散点图、饼图、K线图,用于统计的盒形图,用于地理数据可视化的地图、热力图、线图,用于关系数据可视化的关系图、treemap、旭日图,多维数据可视化的平行坐标,还有用于 BI 的漏斗图,仪表盘,并且支持图与图之间的混搭。
官方网站:https://echarts.apache.org/zh/index.html
npm install --save echarts@4.1.0
2.编写页面
setChartData(data) { // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('chart')) // 指定图表的配置项和数据 var option = { title: { text: '观看课程人数统计' }, xAxis: { data: data.xData }, yAxis: { minInterval: 1 }, series: [{ type: 'line', data: data.yData }] } // 使用刚指定的配置项和数据显示图表。
Nacos 是阿里巴巴推出来的一个新开源项目,是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施
2.1、下载地址和版本
下载地址:https://github.com/alibaba/nacos/releases
下载版本:nacos-server-1.1.4.tar.gz或nacos-server-1.1.4.zip,解压任意目录即可
2.2、启动nacos服务
(1) Linux/Unix/Mac
启动命令(standalone代表着单机模式运行,非集群模式)
启动命令:sh startup.sh -m standalone
(2)Windows
启动方式,cmd打开,执行命令: startup.cmd -m standalone。
访问:http://localhost:8848/nacos
用户名密码:nacos/nacos
把service_vod微服务注册到注册中心,其他模块注册步骤相同
3.1、在service模块配置pom
配置Nacos客户端的pom依赖
<!-- 服务注册 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 服务调用feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
3.2、配置service_vod
配置application.properties,在客户端微服务中添加注册Nacos服务的配置信息
# nacos服务地址
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
3.3、添加Nacos客户端注解
在service_vod微服务启动类中添加注解
@EnableDiscoveryClient
3.4、启动客户端微服务
启动注册中心,访问localhost:8848
启动已注册的微服务,可以在Nacos服务列表中看到被注册的微服务
1.1、Gateway概述
Spring cloud gateway是spring官方基于Spring 5.0、Spring Boot2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供简单、有效和统一的API路由管理方式,Spring Cloud Gateway作为Spring Cloud生态系统中的网关,目标是替代Netflix Zuul,其不仅提供统一的路由方式,并且还基于Filter链的方式提供了网关基本的功能,例如:安全、监控/埋点、限流等。
1.2、Gateway核心概念
网关提供API全托管服务,丰富的API管理功能,辅助企业管理大规模的API,以降低管理成本和安全风险,包括协议适配、协议转发、安全策略、防刷、流量、监控日志等贡呢。一般来说网关对外暴露的URL或者接口信息,我们统称为路由信息。如果研发过网关中间件或者使用过Zuul的人,会知道网关的核心是Filter以及Filter Chain(Filter责任链)。Sprig Cloud Gateway也具有路由和Filter的概念。下面介绍一下Spring Cloud Gateway中几个重要的概念。
(1)路由。路由是网关最基础的部分,路由信息有一个ID、一个目的URL、一组断言和一组Filter组成。如果断言路由为真,则说明请求的URL和配置匹配
(2)断言。Java8中的断言函数。Spring Cloud Gateway中的断言函数输入类型是Spring5.0框架中的ServerWebExchange。Spring Cloud Gateway中的断言函数允许开发者去定义匹配来自于http request中的任何信息,比如请求头和参数等。
(3)过滤器。一个标准的Spring webFilter。Spring cloud gateway中的filter分为两种类型的Filter,分别是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理
如图所示,Spring cloud Gateway发出请求。然后再由Gateway Handler Mapping中找到与请求相匹配的路由,将其发送到Gateway web handler。Handler再通过指定的过滤器链将请求发送到实际的服务执行业务逻辑,然后返回。
(1)在ggkt_parent下创建service_gateway
<dependencies> <dependency> <groupId>com.huicode</groupId> <artifactId>service_util</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- 网关 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!-- 服务注册 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> </dependencies>
@SpringBootApplication
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
(1)编写application.properties
# 服务端口 server.port=8333 # 服务名 spring.application.name=service-gateway # nacos服务地址 spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 #使用服务发现路由 spring.cloud.gateway.discovery.locator.enabled=true #service-vod模块配置,路由 #设置路由id spring.cloud.gateway.routes[0].id=service-vod #设置路由的uri spring.cloud.gateway.routes[0].uri=lb://service-vod #设置路由断言,代理servicerId为auth-service的/auth/路径 spring.cloud.gateway.routes[0].predicates= Path=/*/vod/** #路径包含vod的就转发到service-vod中
每一个微服务都要在网关配置文件上写好路由。
跨域本质是浏览器对于ajax请求的一种安全限制:一个页面发起的ajax请求,只能是与当前页域名相同的路径,这能有效的阻止跨站攻击。因此:跨域问题 是针对ajax的一种限制。但是这却给我们的开发带来了不便,而且在实际生产环境中,肯定会有很多台服务器之间交互,地址和端口都可能不同。
之前我们通过服务器添加注解实现,现在我们跨域通过网关来解决跨域问题。
@Configuration
public class CorsConfig {
//处理跨域
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
**注意:**目前我们已经在网关做了跨域处理,那么service服务就不需要再做跨域处理了,将之前在controller类上添加过@CrossOrigin标签的去掉
在ggkt_parent -> service_client -> service_user_client
<dependencies> <dependency> <groupId>com.atguigu</groupId> <artifactId>service_util</artifactId> <version>0.0.1-SNAPSHOT</version> <scope>provided </scope> </dependency> <dependency> <groupId>com.huicode</groupId> <artifactId>model</artifactId> <version>0.0.1-SNAPSHOT</version> <scope>provided </scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <scope>provided </scope> </dependency> <!-- 服务调用feign --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <scope>provided </scope> </dependency> </dependencies>
@FeignClient(value = "service-user")
public interface UserInfoFeignClient {
@GetMapping("/admin/user/userInfo/inner/getById/{id}")
UserInfo getById(@PathVariable Long id);
}
<dependencies>
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>service_user_client</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.huicode")
@ComponentScan(basePackages = "com.huicode")
public class ServiceActivityApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceActivityApplication.class, args);
}
}
远程调用,根据用户id获取用户信息
@Service public class CouponInfoServiceImpl extends ServiceImpl<CouponInfoMapper, CouponInfo> implements CouponInfoService { @Autowired private UserInfoFeignClient userInfoFeignClient; //封装用户昵称和手机号 private CouponUse getUserInfoBycouponUse(CouponUse couponUse) { Long userId = couponUse.getUserId(); if(!StringUtils.isEmpty(userId)) { UserInfo userInfo = userInfoFeignClient.getById(userId); if(userInfo != null) { couponUse.getParam().put("nickName", userInfo.getNickName()); couponUse.getParam().put("phone", userInfo.getPhone()); } } return couponUse; } }
同步菜单:公众号的同步菜单使用stream流来过滤,有点意思拿出来看看。
List
//获取全部菜单 @Override public List<MenuVo> findMenuInfo() { List<MenuVo> list = new ArrayList<>(); List<Menu> menuList = baseMapper.selectList(null); List<Menu> oneMenuList = menuList.stream().filter(menu -> menu.getParentId().longValue() == 0).collect(Collectors.toList()); for(Menu oneMenu : oneMenuList) { MenuVo oneMenuVo = new MenuVo(); BeanUtils.copyProperties(oneMenu, oneMenuVo); List<Menu> twoMenuList = menuList.stream() .filter(menu -> menu.getParentId().longValue() == oneMenu.getId()) .sorted(Comparator.comparing(Menu::getSort)) .collect(Collectors.toList()); List<MenuVo> children = new ArrayList<>(); for(Menu twoMenu : twoMenuList) { MenuVo twoMenuVo = new MenuVo(); BeanUtils.copyProperties(twoMenu, twoMenuVo); children.add(twoMenuVo); } oneMenuVo.setChildren(children); list.add(oneMenuVo); } return list; }
}
}
# 扩展 同步菜单:公众号的同步菜单使用stream流来过滤,有点意思拿出来看看。 List<Menu> twoMenuList = menuList**.stream()** **.filter(**menu -> menu.getParentId().longValue() == oneMenu.getId()) **.sorted**(Comparator.comparing(Menu::getSort)) **.collect**(Collectors.toList()); ```java //获取全部菜单 @Override public List<MenuVo> findMenuInfo() { List<MenuVo> list = new ArrayList<>(); List<Menu> menuList = baseMapper.selectList(null); List<Menu> oneMenuList = menuList.stream().filter(menu -> menu.getParentId().longValue() == 0).collect(Collectors.toList()); for(Menu oneMenu : oneMenuList) { MenuVo oneMenuVo = new MenuVo(); BeanUtils.copyProperties(oneMenu, oneMenuVo); List<Menu> twoMenuList = menuList.stream() .filter(menu -> menu.getParentId().longValue() == oneMenu.getId()) .sorted(Comparator.comparing(Menu::getSort)) .collect(Collectors.toList()); List<MenuVo> children = new ArrayList<>(); for(Menu twoMenu : twoMenuList) { MenuVo twoMenuVo = new MenuVo(); BeanUtils.copyProperties(twoMenu, twoMenuVo); children.add(twoMenuVo); } oneMenuVo.setChildren(children); list.add(oneMenuVo); } return list; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。