当前位置:网站首页>Day102. Shangyitong project
Day102. Shangyitong project
2022-07-16 08:24:00 【Fireworks youth·】
Catalog
2、 Unified return result (delete test )
3、 Implement the query interface with conditions and paging
One 、 Project introduction
1、 The business process

2、 System architecture
Several aspects to consider in architecture design : cost 、 performance ( Distributed deployment , Introduce caching )、 Extensibility ( Use the microservice architecture , Introduce message middleware )、 High availability : colony 、 Load balancing 、 Security .

Git: Distributed version control tools
Docker: Container virtualization technology
Nginx: Reverse proxy 、 Load balancing 、 Dynamic and static separation .
colony : Prevent single machine failure 、 Users have no perception .
Redis colony , At least six sets of three masters and three slaves
ELK Log system
Kibana: Data presentation
Logstash: Storage , Record 、 Analyze user behavior
ElasticSearch: Search engine
Two 、 Project structures,

2、 Project construction is layered
*jar:java Basic engineering
*war:web Project package
*pom: The parent project


Only when it is used can it be downloaded ,
1、 To configure Swagger2
In the development mode of front end and back end separation ,api Documentation is the best way to communicate .Swagger Generate from the code Web Version Description Document .
Swagger Is a specification and complete framework , Used to generate 、 describe 、 Invocation and visualization RESTful Style Web service .
- timeliness ( After the interface changes , Be able to timely and accurately inform relevant front and back-end developers )
- Normative ( And ensure the standardization of the interface , Such as the address of the interface , Request mode , Parameter and response formats and error messages )
- Uniformity ( Interface information is consistent , There will be no inconsistency of document versions obtained by developers , And there are differences )
- Testability ( Test directly on the interface document , In order to understand the business )
1. common Now create a sub module service_utils, Create configuration class Swagger2Config @EnableSwagger2
package com.atguigu.yygh.common.config;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.service.Contact;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webApi")
.apiInfo(webApiInfo())
.select()
// Display only api The page under the path
//.paths(Predicates.and(PathSelectors.regex("/api/.*")))
.build();
}
@Bean
public Docket adminApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("adminApi")
.apiInfo(adminApiInfo())
.select()
// Display only admin The page under the path
.paths(Predicates.and(PathSelectors.regex("/admin/.*")))
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title(" Website -API file ")
.description(" This document describes the definition of website microservice interface ")
.version("1.0")
.contact(new Contact("atguigu", "http://atguigu.com", "[email protected]"))
.build();
}
private ApiInfo adminApiInfo(){
return new ApiInfoBuilder()
.title(" Background management system -API file ")
.description(" This document describes the microservice interface definition of the background management system ")
.version("1.0")
.contact(new Contact("atguigu", "http://atguigu.com", "[email protected]"))
.build();
}
}2. service Project add dependency
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>service_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>3. Start the class to add comments
@SpringBootApplication
@ComponentScan(basePackages = {"com.atguigu"}) // Scan other project configurations
public class ServiceHospApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceHospApplication.class, args);
}
}4. Start access api, test
http://localhost:8201/swagger-ui.html

5、 Optimize
@Api(description = " Hospital set interface ") Define interface description and parameter description
@ApiOperation(value = " Hospital settings list ")

2、 Unified return result (delete test )
In the project, we will respond Encapsulated into json return , Generally, we will put all The data format of the interface is unified , Make the front end (iOS Android, Web) More consistent operation of data 、 Relaxed . Save front-end development code .
1、json
(1) object :{“name”:”zhang3”,“age”:33}
(2) aggregate :
[{“name”:”zhang3”,“age”:33},
{“name”:”zhang3”,“age”:33},{“name”:”zhang3”,“age”:33}]
2、 Unified format
{
"success": true,
"code": 20000,
"message": " success ",
"data": {
"items": [
{
"id": "1",
"name": " Lau Andy ",
"intro": " Graduated from the Department of mathematics of Normal University , Love education , Teaching mathematical thinking 6 Over the year "
}
]
}
}stay common Create sub modules under modules common_utils
1. Create interface definition return code
public class ResultCode {
public static Integer SUCCESS = 20000;
public static Integer ERROR = 20001;
}2. Encapsulate the result class
package com.atguigu.yygh.common;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
/**
* @Date 2022/7/13 11:27
* @Author by:Plisetsky
*/
@Data
public class R {
@ApiModelProperty(value = " The success of ")
private Boolean success;
@ApiModelProperty(value = " Return code ")
private Integer code;
@ApiModelProperty(value = " Return message ")
private String message;
@ApiModelProperty(value = " Return the data ")
private Map<String, Object> data = new HashMap<String, Object>();
private R(){}
public static R ok(){
R r = new R();
r.setSuccess(true);
r.setCode(ResultCode.SUCCESS);
r.setMessage(" success ");
return r;
}
public static R error(){
R r = new R();
r.setSuccess(false);
r.setCode(ResultCode.ERROR);
r.setMessage(" Failure ");
return r;
}
public R success(Boolean success){
this.setSuccess(success);
return this;
}
public R message(String message){
this.setMessage(message);
return this;
}
public R code(Integer code){
this.setCode(code);
return this;
}
public R data(String key, Object value){
this.data.put(key, value);
return this;
}
public R data(Map<String, Object> map){
this.setData(map);
return this;
}
}
3. Introduce dependencies
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>common_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>4. controller Interface modification
// Query all hospital settings
@ApiOperation(value = " Hospital settings list ")
@GetMapping("findAll")
public R findAll() { // Result object encapsulation
List<HospitalSet> list = hospitalSetService.list();
return R.ok().data("list",list);
}
// Delete Test introduction swagger2
@ApiOperation(value = " Hospital settings deleted ")
@DeleteMapping("{id}") // If the type does not match , Impact velocity
public R removeById(@PathVariable Long id){
boolean remove = hospitalSetService.removeById(id);
return R.ok();
}
3、 Implement the query interface with conditions and paging
1. Analysis interface
Confirm demand :
Required parameters : The current page , Records per page
Return value :R (Page Paging object )
2. Add paging plug-ins
@Configuration
@EnableTransactionManagement
@MapperScan("com.atguigu.yygh.hosp.mapper")
public class HospConfig {
// Paging plug-ins
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}3. Implementation interface
@ApiOperation(value = " Paging query hospital settings ")
@GetMapping("{page}/{limit}")
public R pageList(@PathVariable Long page,
@PathVariable Long limit){
//1. Create paging objects , Pass in the parameter The current page Records per page
Page<HospitalSet> pageParam = new Page<>(page,limit);
//2. Paging query
Page<HospitalSet> pageModel = hospitalSetService.page(pageParam);
//3. Encapsulation results
return R.ok().data("pageModel",pageModel);
}4. test

Paging query with parameters
1. Analysis interface
Confirm demand :
Required parameters : The current page 、 Records per page 、 Query criteria object (vo:View Object)
Return value :R (Page Paging object )
2. Implementation interface
@RequestBody :Json turn Java
@ResponseBod:Java turn Json strand
ApiOperation(value = " Condition paging query hospital settings ")
//@GetMapping("pageQuery/{page}/{limit}")
@PostMapping("pageQuery/{page}/{limit}")
public R pageList(@PathVariable Long page,
@PathVariable Long limit,
@RequestBody HospitalSetQueryVo hospitalSetQueryVo){
//1. To obtain parameters , Void test , Deposit in wrapper Conditional query constructor
QueryWrapper<HospitalSet> wrapper = new QueryWrapper<>();
String hosname = hospitalSetQueryVo.getHosname();
String hoscode = hospitalSetQueryVo.getHoscode();
if(!StringUtils.isEmpty(hosname)){
// Fuzzy query
wrapper.like("hosname",hosname);
}
if(!StringUtils.isEmpty(hoscode)){
wrapper.eq("hoscode",hoscode);
}
//2. Create paging objects , Pass in the parameter The current page Records per page
Page<HospitalSet> pageParam = new Page<>(page,limit);
//3. Paging query , Pass in wrapper Conditional query constructor
Page<HospitalSet> pageModel = hospitalSetService.page(pageParam,wrapper);
//4. The encapsulation result returns
return R.ok().data("pageModel",pageModel);
}

4、 newly added
1. Analysis interface
Required parameters :HospitalSet
Return value :R.ok()
2. Implementation interface
@ApiOperation(value = " New hospital settings ")
@PostMapping("save")
public R save(@RequestBody HospitalSet hospitalSet){
boolean save = hospitalSetService.save(hospitalSet);
return save ? R.ok() : R.error();
}Be careful When testing, compare the time with id Delete , It will generate automatically ,hoscode Can't repeat

Mysql5.5 There will be problems :
5、 modify
1. Analysis interface
2. Implementation interface
@ApiOperation(value = " according to id Query hospital settings ")
@GetMapping("getHospsetById/{id}")
public R getById(@PathVariable Long id){
HospitalSet hospitalSet = hospitalSetService.getById(id);
return R.ok().data("hospitalSet",hospitalSet);
}
@ApiOperation(value = " Modify hospital settings ")
@PostMapping("update")
public R update(@RequestBody HospitalSet hospitalSet){
//hospitalSet, There is id
boolean save = hospitalSetService.updateById(hospitalSet);
return save ? R.ok() : R.error();
}6、 Batch deletion
1. Analyze requirements
Parameters :List<Long> Checked Id aggregate
Return value :R.ok()
2. Interface implementation
// Delete Test introduction swagger2
@ApiOperation(value = " Delete hospital settings in batch ")
@DeleteMapping("batchRemove")
public R removeById(@RequestBody List<Long> idList){
boolean remove = hospitalSetService.removeByIds(idList);
return remove ? R.ok() : R.error();
}
7、 Lock hospital settings
1. Analyze requirements
Parameters :id,status
Return value :R.ok()
2. Interface implementation
// Hospital settings lock and unlock
@PutMapping("lockHospitalSet/{id}/{status}")
public R lockHospitalSet(@PathVariable Long id,
@PathVariable Integer status) {
//1. First query
HospitalSet hospitalSet = hospitalSetService.getById(id);
//2. Post update
hospitalSet.setStatus(status);
boolean update = hospitalSetService.updateById(hospitalSet);
return update ? R.ok() : R.error();
}8、 Unified exception handling
Out of system trust 、 Safety considerations , Do not expose error messages
service_utils Under the project
1. Add result dependency
<dependencies>
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>common_utils</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
</dependencies>1. Create a unified exception handler AOP?
@ControllerAdvice //AOP Section oriented programming
public class GlobalExceptionHandler {
// Grab runtime exception
@ExceptionHandler(Exception.class)
@ResponseBody
public R error(Exception e){
e.printStackTrace();
return R.error();
}
// Special exception handling
@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public R error(ArithmeticException e){
e.printStackTrace();
return R.error().message(" Special exception handling ");
}
}
Custom exception
service_utils Under the project
1. handler In bag Create custom exception
// Abnormal appointment
@Data
@AllArgsConstructor
@NoArgsConstructor
public class YyghException extends RuntimeException{
@ApiModelProperty(value = " Status code ")
private Integer code;
@ApiModelProperty(value = " Abnormal information ")
private String msg;
}2. Abnormal controller Add method
// Custom exception handling
@ExceptionHandler(YyghException.class)
@ResponseBody
public R error(YyghException e){
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMessage());
}3. Method throws an exception manually
// Query all hospital settings
@ApiOperation(value = " Hospital settings list ")
@GetMapping("findAll")
public R findAll() { // Result object encapsulation
try {
int i = 10/0;
} catch (Exception e) {
e.printStackTrace();
throw new YyghException(20001," Custom exception ");
}
List<HospitalSet> list = hospitalSetService.list();
return R.ok().data("list",list);
}

边栏推荐
- Spot gold knowledge that Xiaobai must learn (24 terms)
- [U - boot] u - boot Sandbox compilation Construction and use Summary
- 【每日一题】二叉搜索树与双向链表
- Heterogeneous computing - heterogeneous chip convergence trend
- 研发中台拆分过程的一些心得总结
- 【每日一题】判断是不是平衡二叉树
- "Everyday Mathematics" serial 59: February 28
- cuDNN神经网络加速库的配置
- Send your code into space and develop "the greatest work" together
- [daily question 1] judge whether it is a balanced binary tree
猜你喜欢

1、 Installation and deployment of MySQL

Fluent: environment construction and project creation
![[U - boot] u - boot Sandbox compilation Construction and use Summary](/img/5f/92d0a1937230d00b4068d65a5a6c29.png)
[U - boot] u - boot Sandbox compilation Construction and use Summary

常见数据集格式+数据集标注

函数式模型

word2vec介绍及CNN在自然语言中的应用

【每日一题】判断是不是平衡二叉树

malloc,vmalloc与kmalloc,free,kfree与vfree的区别和联系

Small program graduation project of wechat enterprise company (1) development outline

Small program graduation project of wechat enterprise company (3) background function
随机推荐
小程序毕设作品之微信企业公司小程序毕业设计(7)中期检查报告
Day102.尚医通项目
【u-boot】u-boot Sandbox编译构建和使用总结
一个XML文件例子
【每日一题】判断是不是平衡二叉树
快速排序·例题二
命令提示符查看某端口占用情况,并清除占用
实在智能获两大全球顶级市场调研机构双料认证,进入全球卓越阵营
leetcode 18. 四数之和
杰理之通话时按样机上的音量键能同步调节手机的通话音量【篇】
Leetcode 454. 四数相加 II
小程序毕设作品之微信企业公司小程序毕业设计(3)后台功能
Small program graduation project of wechat enterprise company (4) opening report
Image style conversion
Suddenly announce the dissolution!
Small program graduation design of wechat enterprise company (2) small program function
Simple canvas animation principle
第54章 业务逻辑之折扣、商品类别实体定义实现
CVPR | self enhanced unpaired image defogging based on density and depth decomposition
猫狗分类-简单CNN