谷粒学院— 第二天
搭建父工程
- guli-parent:在线教学根目录(父工程),管理四个子模块:
- canal-client:canal数据库表同步模块(统计同步数据)
- common:公共模块父节点
- common-util:工具类模块,所有模块都可以依赖于它
- service-base:service服务的base包,包含service服务的公共配置类,所有service模块依赖于它
- spring-security:认证与授权模块,需要认证授权的service服务依赖于它
- infrastructure:基础服务模块父节点
- api-gateway:api网关服务
- service:api接口服务父节点
- service-acl:用户权限管理api接口服务(用户管理、角色管理和权限管理等)
- service-cms:cms api接口服务
- service-edu:教学相关api接口服务
- service-msm:短信api接口服务
- service-order:订单相关api接口服务
- service-oss:阿里云oss api接口服务
- service-statistics:统计报表api接口服务
- service-ucenter:会员api接口服务
- service-vod:视频点播api接口服务
创建sprigboot工程guli-parent
在idea开发工具中,使用 Spring Initializr 快速初始化一个 Spring Boot 模块,版本使用:2.2.1.RELEASE
-
配置 pom.xml
-
节点后面添加 pom类型
-
<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.atguigu</groupId> <artifactId>guli_parent</artifactId> <packaging>pom</packaging> <version>0.0.1-SNAPSHOT</version> <name>guli_parent</name> <description>Demo project for Spring Boot</description>
-
整个pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<modules>
<module>service</module>
<module>common</module>
<module>infrastructure</module>
</modules>
<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.atguigu</groupId>
<artifactId>guli_parent</artifactId>
<packaging>pom</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>guli_parent</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<guli.version>0.0.1-SNAPSHOT</guli.version>
<mybatis-plus.version>3.0.5</mybatis-plus.version>
<velocity.version>2.0</velocity.version>
<swagger.version>2.7.0</swagger.version>
<aliyun.oss.version>2.8.3</aliyun.oss.version>
<jodatime.version>2.10.1</jodatime.version>
<poi.version>3.17</poi.version>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<commons-io.version>2.6</commons-io.version>
<httpclient.version>4.5.1</httpclient.version>
<jwt.version>0.7.0</jwt.version>
<aliyun-java-sdk-core.version>4.3.3</aliyun-java-sdk-core.version>
<aliyun-sdk-oss.version>3.1.0</aliyun-sdk-oss.version>
<aliyun-java-sdk-vod.version>2.15.2</aliyun-java-sdk-vod.version>
<aliyun-java-vod-upload.version>1.4.11</aliyun-java-vod-upload.version>
<aliyun-sdk-vod-upload.version>1.4.13</aliyun-sdk-vod-upload.version>
<fastjson.version>1.2.28</fastjson.version>
<gson.version>2.8.2</gson.version>
<json.version>20170516</json.version>
<commons-dbutils.version>1.7</commons-dbutils.version>
<canal.client.version>1.1.0</canal.client.version>
<docker.image.prefix>zx</docker.image.prefix>
<cloud-alibaba.version>0.2.2.RELEASE</cloud-alibaba.version>
</properties>
<dependencyManagement>
<dependencies>
<!--Spring Cloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${cloud-alibaba.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>
<!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>${velocity.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>
<!--aliyunOSS-->
<!-- <dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun.oss.version}</version>
</dependency>-->
<!--日期时间工具-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime.version}</version>
</dependency>
<!--xls-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<!--xlsx-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<!--commons-io-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>${jwt.version}</version>
</dependency>
<!--aliyun-->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>${aliyun-java-sdk-core.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun-sdk-oss.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-vod</artifactId>
<version>${aliyun-java-sdk-vod.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-vod-upload</artifactId>
<version>${aliyun-java-vod-upload.version}</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-sdk-vod-upload</artifactId>
<version>${aliyun-sdk-vod-upload.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>${commons-dbutils.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.otter</groupId>
<artifactId>canal.client</artifactId>
<version>${canal.client.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
搭建service模块
-
在父工程guli-parent下面创建模块service
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?> <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>guli_parent</artifactId> <groupId>com.atguigu</groupId> <version>0.0.1-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>service</artifactId> <packaging>pom</packaging> <modules> <module>service_edu</module> <module>service_oss</module> <module>service_vod</module> <module>service_cms</module> <module>service_msm</module> <module>service_ucenter</module> <module>service_order</module> <module>service_statistics</module> <module>service_acl</module> </modules> <dependencies> <dependency> <groupId>com.atguigu</groupId> <artifactId>service_base</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> <!-- <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> <!–hystrix依赖,主要是用 @HystrixCommand –> --> <!--服务熔断--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> <!--服务注册--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!--服务调用--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--mybatis-plus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- velocity 模板引擎, Mybatis Plus 代码生成器需要 --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> </dependency> <!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> </dependency> <!--lombok用来简化实体类:需要安装lombok插件--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--xls--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> </dependency> <!--httpclient--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <!--commons-io--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> </dependency> <!--gson--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> <build> <!--<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources>--> <!--打包规则,打包时将resource文件夹打包进去--> <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> </project>
搭建service-edu模块
resources目录下创建文件 application.properties
# 服务端口
server.port=8001
# 服务名
spring.application.name=service-edu
# 环境设置:dev、test、prod
spring.profiles.active=dev
# mysql数据库连接
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/guli?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
创建MP代码生成器
strategy.setInclude("edu_teacher");
编写后台管理api接口
@Autowired
private EduTeacherService teacherService;
//1、查询讲师表所有数据
//rest风格
@ApiOperation(value = "所有讲师列表")
@GetMapping("/findAll")
public ResultData findAllTeacher(){
List<EduTeacher> list = teacherService.list(null);
return ResultData.ok().data("items",list);
}
创建SpringBoot配置类
package com.atguigu.serviceedu.config;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author wangJingKai
* @Date 2021-08-16 10:14
* @Version 1.0
*/
@Configuration
@MapperScan("com.atguigu.serviceedu.mapper")
public class EduConfig {
/*
*逻辑删除插件
* */
@Bean
public ISqlInjector sqlInjector(){
return new LogicSqlInjector();
}
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
创建SpringBoot启动类
package com.atguigu.serviceedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
/**
* @Author wangJingKai
* @Date 2021-08-16 10:13
* @Version 1.0
*/
@SpringBootApplication
@ComponentScan(basePackages = {"com.atguigu"})
public class EduApplication {
public static void main(String[] args) {
SpringApplication.run(EduApplication.class,args);
}
}
运行启动类
访问http://localhost:8001/eduservice/teacher
得到json数据
统一返回的json时间格式
默认情况下json时间格式带有时区,并且是世界标准时间,和我们的时间差了八个小时
在application.properties中设置
#返回json的全局时间格式
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
讲师逻辑删除功能
-
EduTeacherController添加删除方法
//2、逻辑删除讲师 @ApiOperation(value = "逻辑删除讲师") @DeleteMapping( "{id}") public boolean removeTeacher( @ApiParam(name = "id",value = "讲师ID", required = true) @PathVariable String id){ return teacherService.removeById(id); }
-
、配置逻辑删除插件
/* *逻辑删除插件 * */ @Bean public ISqlInjector sqlInjector(){ return new LogicSqlInjector(); }
-
测试
数据库中的is_deleted字段被修改为1
跨域配置
1、什么是跨域?
浏览器从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域 。前后端
分离开发中,需要考虑ajax跨域的问题。
2、如何解决?
在Controller类上添加注解
@CrossOrigin //跨域
Swagger2介绍
前后端分离开发模式中,api文档是最好的沟通方式。
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
- 及时性 (接口变更后,能够及时准确地通知相关前后端开发人员)
- 规范性 (并且保证接口的规范性,如接口的地址,请求方式,参数及响应格式和错误信息)
- 一致性 (接口信息一致,不会出现因开发人员拿到的文档版本不一致,而出现分歧)
- 可测性 (直接在接口文档上进行测试,以方便理解业务)
配置Swagger2
创建common模块
在guli-parent下创建模块common
在common中引入相关依赖
<?xml version="1.0" encoding="UTF-8"?>
<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>guli_parent</artifactId>
<groupId>com.atguigu</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>common</artifactId>
<packaging>pom</packaging>
<modules>
<module>service_base</module>
<module>common_utils</module>
</modules>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided </scope>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<scope>provided </scope>
</dependency>
<!--lombok用来简化实体类:需要安装lombok插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided </scope>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<scope>provided </scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<scope>provided </scope>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- spring2.X集成redis所需common-pool2-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
</dependencies>
</project>
在common下面创建子模块service-base
在模块service-base中,创建swagger的配置类
package com.atguigu.servicebase;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
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;
/**
* @Author wangJingKai
* @Date 2021-08-16 10:43
* @Version 1.0
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
// .paths(Predicates.not(PathSelectors.regex("/admin/.*")))
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("网站-课程中心API文档")
.description("本文档描述了课程中心微服务接口定义")
.version("1.0")
.contact(new Contact("wjk", "http://atguigu.com", "302658980@qq.com"))
.build();
}
}
在模块service模块中引入service-base
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>service-base</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
在service-edu启动类上添加注解,进行测试
@SpringBootApplication
@ComponentScan(basePackages = {"com.atguigu"})
public class EduApplication {
public static void main(String[] args) {
SpringApplication.run(EduApplication.class,args);
}
}
定义接口说明和参数说明
定义在类上:@Api
定义在方法上:@ApiOperation
定义在参数上:@ApiParam
统一返回数据格式
项目中我们会将响应封装成json返回,一般我们会将所有接口的数据格式统一, 使前端(iOS Android,
Web)对数据的操作更一致、轻松。
一般情况下,统一返回数据格式没有固定的格式,只要能描述清楚返回的数据状态以及要返回的具体数
据就可以。但是一般会包含状态码、返回消息、数据这几部分内容
例如,我们的系统要求返回的基本数据格式如下:
列表:
{
"success": true,
"code": 20000,
"message": "成功",
"data": {
"items": [
{
"id": "1",
"name": "刘德华",
"intro": "毕业于师范大学数学系,热爱教育事业,执教数学思维6年有余"
}
]
}
}
分页:
"success": true,
"code": 20000,
"message": "成功",
"data": {
"total": 17,
"rows": [
{
"id": "1",
"name": "刘德华",
"intro": "毕业于师范大学数学系,热爱教育事业,执教数学思维6年有余"
}
]
}
}
没有返回数据:
{
"success": true,
"code": 20000,
"message": "成功",
"data": {}
}
失败:
{
"success": false,
"code": 20001,
"message": "失败",
"data": {}
}
因此,我们定义统一结果
{
"success": 布尔, //响应是否成功
"code": 数字, //响应码
"message": 字符串, //返回消息
"data": HashMap //返回数据,放在键值对中
}
创建统一结果返回类
在common模块下创建子模块common-utils
创建接口定义返回码
package com.atguigu.commonutils;
/**
* @Author wangJingKai
* @Date 2021-08-16 11:21
* @Version 1.0
*/
public interface ResultCode {
public static Integer SUCCESS = 20000; //成功
public static Integer ERROR = 20000; //失败
}
创建结果类
package com.atguigu.commonutils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
/**
* @Author wangJingKai
* @Date 2021-08-16 11:24
* @Version 1.0
*/
@Data
public class ResultData {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty(value = "返回码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String message;
@ApiModelProperty(value = "返回数据")
private Map<String, Object> data = new HashMap<String, Object>();
//构造器私有化
private ResultData() {
}
//成功静态方法
public static ResultData ok() {
ResultData resultData = new ResultData();
resultData.setSuccess(true);
resultData.setCode(ResultCode.SUCCESS);
resultData.setMessage("成功");
return resultData;
}
//失败静态方法
public static ResultData error() {
ResultData resultData = new ResultData();
resultData.setSuccess(false);
resultData.setCode(ResultCode.ERROR);
resultData.setMessage("失败");
return resultData;
}
public ResultData success(Boolean success) {
this.setSuccess(success);
return this;
}
public ResultData message(String message) {
this.setMessage(message);
return this;
}
public ResultData code(Integer code) {
this.setCode(code);
return this;
}
public ResultData data(String key, Object value) {
this.data.put(key, value);
return this;
}
public ResultData data(Map<String, Object> map) {
this.setData(map);
return this;
}
}
统一返回结果使用
在service模块中添加依赖
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>common_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
修改Controller中的返回结果
//1、查询讲师表所有数据
//rest风格
@ApiOperation(value = "所有讲师列表")
@GetMapping("/findAll")
public ResultData findAllTeacher(){
List<EduTeacher> list = teacherService.list(null);
return ResultData.ok().data("items",list);
}
//2、逻辑删除讲师
@ApiOperation(value = "逻辑删除讲师")
@DeleteMapping( "{id}")
public ResultData removeTeacher(
@ApiParam(name = "id",value = "讲师ID", required = true)
@PathVariable String id){
return teacherService.removeById(id)?ResultData.ok():ResultData.error();
}
分页
MyBatisPlusConfig中配置分页插件
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
分页Controller方法
//3、分页查询讲师的方法
@GetMapping("pageTeacher/{current}/{limit}")
public ResultData pageListTeacher(@PathVariable long current,
@PathVariable long limit){
//创建page对象
Page<EduTeacher> pageTeacher = new Page<>(current,limit);
//调用分页方法
//调用方法时,底层封装,把分页所有数据封装到pageTeacher
teacherService.page(pageTeacher,null);
// 也可以直接把pageTeacher对象传入,会自动分页
//return ResultData.ok().data("result",pageTeacher);
long total = pageTeacher.getTotal(); //总记录数
List<EduTeacher> records = pageTeacher.getRecords(); //数据list集合
return ResultData.ok().data("total",total).data("rows",records);
条件查询
根据讲师名称name,讲师头衔level、讲师入驻时间gmt_create(时间段)查询
创建查询对象
创建com.atguigu.serviceedu.entity.vo包,创建TeacherQuery.java查询对象
package com.atguigu.serviceedu.entity.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* @Author wangJingKai
* @Date 2021-08-16 14:26
* @Version 1.0
*/
@ApiModel(value = "Teacher查询对象", description = "讲师查询对象封装")
@Data
public class TeacherQuery implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "教师名称,模糊查询")
private String name;
@ApiModelProperty(value = "头衔 1高级讲师 2首席讲师")
private Integer level;
@ApiModelProperty(value = "查询开始时间", example = "2019-01-01 10:10:10")
private String begin;//注意,这里使用的是String类型,前端传过来的数据无需进行类型转换
@ApiModelProperty(value = "查询结束时间", example = "2019-12-01 10:10:10")
private String end;
}
service
-
Controller
//4、条件查询带分页 @PostMapping("pageTeacherCondition/{current}/{limit}") public ResultData pageTeacherCondition(@PathVariable long current, @PathVariable long limit, @RequestBody(required = false) TeacherQuery teacherQuery){ //创建Page对象 Page<EduTeacher> pageTeacher = new Page<>(current,limit); //构造条件 QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>(); String name = teacherQuery.getName(); Integer level = teacherQuery.getLevel(); String begin = teacherQuery.getBegin(); String end = teacherQuery.getEnd(); //多条件组合查询,判断条件值是否为空,不为空拼接条件 if (!StringUtils.isEmpty(name)){ wrapper.like("name",name); } if (!StringUtils.isEmpty(level)){ wrapper.eq("level",level); } if (!StringUtils.isEmpty(begin)){ wrapper.ge("gmt_create",begin); } if (!StringUtils.isEmpty(end)){ wrapper.le("gmt_create",end); } //排序 wrapper.orderByDesc("gmt_modified"); //调用方法实现条件分页查询 teacherService.page(pageTeacher,wrapper); long total = pageTeacher.getTotal();//总记录数 List<EduTeacher> records = pageTeacher.getRecords(); //数据list集合 return ResultData.ok().data("total",total).data("rows",records); }
自动填充封装
在service-base模块中添加
创建包handler,创建自动填充类 MyMetaObjectHandler
package com.atguigu.servicebase.handler;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* @Author wangJingKai
* @Date 2021-08-16 15:14
* @Version 1.0
*/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.setFieldValByName("gmtCreate", new Date(), metaObject);
this.setFieldValByName("gmtModified", new Date(), metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
this.setFieldValByName("gmtModified", new Date(), metaObject);
}
}
在实体类添加自动填充注解
@ApiModelProperty(value = "逻辑删除 1(true)已删除, 0(false)未删除")
@TableLogic
private Boolean isDeleted;
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private Date gmtCreate;
@ApiModelProperty(value = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date gmtModified;
controller方法定义
package com.atguigu.serviceedu.controller;
import com.atguigu.commonutils.ResultData;
import com.atguigu.servicebase.exceptionhandler.WangJKException;
import com.atguigu.serviceedu.entity.EduTeacher;
import com.atguigu.serviceedu.entity.vo.TeacherQuery;
import com.atguigu.serviceedu.service.EduTeacherService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* <p>
* 讲师 前端控制器
* </p>
*
* @author wjk
* @since 2021-08-16
*/
@Api(tags = "讲师管理",description = "讲师")
@RestController
@RequestMapping("/serviceedu/edu-teacher")
// @CrossOrigin 当在gateway中配置了跨域后,就不能在这里加上跨域注解
public class EduTeacherController {
//注入servic
@Autowired
private EduTeacherService teacherService;
//1、查询讲师表所有数据
//rest风格
@ApiOperation(value = "所有讲师列表")
@GetMapping("/findAll")
public ResultData findAllTeacher(){
List<EduTeacher> list = teacherService.list(null);
return ResultData.ok().data("items",list);
}
//2、逻辑删除讲师
@ApiOperation(value = "逻辑删除讲师")
@DeleteMapping( "{id}")
public ResultData removeTeacher(
@ApiParam(name = "id",value = "讲师ID", required = true)
@PathVariable String id){
return teacherService.removeById(id)?ResultData.ok():ResultData.error();
}
//3、分页查询讲师的方法
@GetMapping("pageTeacher/{current}/{limit}")
public ResultData pageListTeacher(@PathVariable long current,
@PathVariable long limit){
//创建page对象
Page<EduTeacher> pageTeacher = new Page<>(current,limit);
//调用分页方法
//调用方法时,底层封装,把分页所有数据封装到pageTeacher
teacherService.page(pageTeacher,null);
// 也可以直接把pageTeacher对象传入,会自动分页
//return ResultData.ok().data("result",pageTeacher);
long total = pageTeacher.getTotal(); //总记录数
List<EduTeacher> records = pageTeacher.getRecords(); //数据list集合
return ResultData.ok().data("total",total).data("rows",records);
}
//4、条件查询带分页
@PostMapping("pageTeacherCondition/{current}/{limit}")
public ResultData pageTeacherCondition(@PathVariable long current,
@PathVariable long limit,
@RequestBody(required = false) TeacherQuery teacherQuery){
//创建Page对象
Page<EduTeacher> pageTeacher = new Page<>(current,limit);
//构造条件
QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>();
String name = teacherQuery.getName();
Integer level = teacherQuery.getLevel();
String begin = teacherQuery.getBegin();
String end = teacherQuery.getEnd();
//多条件组合查询,判断条件值是否为空,不为空拼接条件
if (!StringUtils.isEmpty(name)){
wrapper.like("name",name);
}
if (!StringUtils.isEmpty(level)){
wrapper.eq("level",level);
}
if (!StringUtils.isEmpty(begin)){
wrapper.ge("gmt_create",begin);
}
if (!StringUtils.isEmpty(end)){
wrapper.le("gmt_create",end);
}
//排序
wrapper.orderByDesc("gmt_modified");
//调用方法实现条件分页查询
teacherService.page(pageTeacher,wrapper);
long total = pageTeacher.getTotal();//总记录数
List<EduTeacher> records = pageTeacher.getRecords(); //数据list集合
return ResultData.ok().data("total",total).data("rows",records);
}
//5、添加讲师接口的方法
@PostMapping("addTeacher")
public ResultData addTeacher(@RequestBody EduTeacher eduTeacher){
boolean flag = teacherService.save(eduTeacher);
return flag?ResultData.ok():ResultData.error();
}
//6、根据讲师Id进行查询
@GetMapping("getTeacherById/{id}")
public ResultData getTeacher(@PathVariable("id")String id){
EduTeacher eduTeacher = teacherService.getById(id);
return ResultData.ok().data("teacher",eduTeacher);
}
//7、讲师修改功能
@PostMapping("updateTeacher")
public ResultData updateTeacher(@RequestBody EduTeacher eduTeacher){
boolean flag = teacherService.updateById(eduTeacher);
return flag?ResultData.ok():ResultData.error();
}
}
统一异常处理
创建统一异常处理器
在service-base中创建统一异常处理类GlobalExceptionHandler.java:
package com.atguigu.servicebase.exceptionhandler;
import com.atguigu.commonutils.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Author wangJingKai
* @Date 2021-08-16 16:01
* @Version 1.0
* @Deprecated 统一异常处理类
*/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)//指定出现什么异常执行这个方法
@ResponseBody //返回json数据
public ResultData error(Exception e){
e.printStackTrace();
return ResultData.error().message("执行了全局异常处理");
}
@ExceptionHandler(ArithmeticException.class)//指定出现什么异常执行这个方法
@ResponseBody //返回json数据
public ResultData error(ArithmeticException e){
e.printStackTrace();
return ResultData.error().message("执行了ArithmeticException异常处理");
}
//自定义异常
@ExceptionHandler(WangJKException.class)//指定出现什么异常执行这个方法
@ResponseBody //返回json数据
public ResultData error(WangJKException e){
log.error(e.getMessage());
e.printStackTrace();
return ResultData.error().code(e.getCode()).message(e.getMsg());
}
}
package com.atguigu.servicebase.exceptionhandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author wangJingKai
* @Date 2021-08-16 16:19
* @Version 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class WangJKException extends RuntimeException {
private Integer code; //状态码
private String msg; //异常信息
}
日志
配置日志级别
日志记录器(Logger)的行为是分等级的。如下表所示:
分为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL
默认情况下,spring boot从控制台打印出来的日志级别只有INFO及以上级别,可以配置日志级别
# 设置日志级别
logging.level.root=WARN
Logback日志
spring boot内部使用Logback作为日志实现的框架。
Logback和log4j非常相似,如果你对log4j很熟悉,那对logback很快就会得心应手。
logback相对于log4j的一些优点:https://blog.csdn.net/caisini_vc/article/details/48551287
配置logback日志
删除application.properties中的日志配置
安装idea彩色日志插件:grep-console
resources 中创建 logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="10 seconds">
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<contextName>logback</contextName>
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。 -->
<property name="log.path" value="E:/实战项目/log" />
<!-- 彩色日志 -->
<!-- 配置格式变量:CONSOLE_LOG_PATTERN 彩色日志格式 -->
<!-- magenta:洋红 -->
<!-- boldMagenta:粗红-->
<!-- cyan:青色 -->
<!-- white:白色 -->
<!-- magenta:洋红 -->
<property name="CONSOLE_LOG_PATTERN"
value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) |%highlight(%-5level) |%blue(%thread) |%blue(%file:%line) |%green(%logger) |%cyan(%msg%n)"/>
<!--输出到控制台-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<!-- 例如:如果此处配置了INFO级别,则后面其他位置即使配置了DEBUG级别的日志,也不会被输出 -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--输出到文件-->
<!-- 时间滚动输出 level为 INFO 日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_info.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 WARN 日志 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_warn.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 ERROR 日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_error.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、以及指定<appender>。
<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
如果未设置此属性,那么当前logger将会继承上级的级别。
-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="INFO">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给mapper下目录配置DEBUG模式,代码如下,这样配置sql语句会打印,其他还是正常DEBUG级别:
-->
<!--开发环境:打印控制台-->
<springProfile name="dev">
<!--可以输出项目中的debug日志,包括mybatis的sql日志-->
<logger name="com.guli" level="INFO" />
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,默认是DEBUG
可以包含零个或多个appender元素。
-->
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="WARN_FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
</springProfile>
<!--生产环境:输出到文件-->
<springProfile name="pro">
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="ERROR_FILE" />
<appender-ref ref="WARN_FILE" />
</root>
</springProfile>
</configuration>
将错误日志输出到文件
GlobalExceptionHandler.java 中
类上添加注解
@Slf4j
异常输出语句
log.error(e.getMessage());
将日志堆栈信息输出到文件
定义工具类
guli-framework-common下创建util包,创建ExceptionUtil.java工具类
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ExceptionUtil {
public static String getMessage(Exception e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
// 将出错的栈信息输出到printWriter中
e.printStackTrace(pw);
pw.flush();
sw.flush();
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (pw != null) {
pw.close();
}
}
return sw.toString();
}
}
调用
log.error(ExceptionUtil.getMessage(e));
GuliException中创建toString方法
@Override
public String toString() {
return "GuliException{" +
"message=" + this.getMessage() +
", code=" + code +
'}';
}
第二天总结: