当前位置:网站首页>Dark horse shopping mall ---2 Distributed file storage fastdfs

Dark horse shopping mall ---2 Distributed file storage fastdfs

2022-06-25 12:04:00 Shuaijie it God

Learning goals

  • == understand FastDFS Workflow ==
  • == Build a file upload micro service ==

  • Album management ( actual combat )

  • Specification parameter management ( actual combat )

  • Commodity classification management ( actual combat )

1 FastDFS

1.1 FastDFS brief introduction

1.1.1 FastDFS Architecture

FastDFS Is an open source lightweight distributed file system , It manages files , Features include : File store 、 File synchronization 、 File access ( Upload files 、 File download ) etc. , The problem of large capacity storage and load balancing is solved . Especially suitable for file - based online services , Such as photo album website 、 Video websites and so on .

FastDFS Tailor-made for the Internet , Redundant backups are fully considered 、 Load balancing 、 Linear capacity expansion mechanism , And focus on high availability 、 High performance and other indicators , Use FastDFS It is easy to set up a high performance file server cluster for file uploading 、 Download and other services .

FastDFS The architecture includes Tracker server and Storage server. Client request Tracker server Upload files 、 download , adopt Tracker server The dispatch is finally made by Storage server Complete file upload and download .

Tracker server The role is load balancing and scheduling , adopt Tracker server When uploading files, you can find Storage server Provide file upload service . Can be tracker Called a tracking server or scheduling server .Storage server The function is to store files , The files uploaded by the client are finally stored in Storage Server ,Storageserver It does not implement its own file system, but uses the operating system's file system to manage files . Can be storage It's called a storage server .

1.1.2 Upload process

After the client uploads the file, the storage server will store the file ID Return to the client , This file ID Index information used to access the file later . File index information includes : Group name , Virtual disk path , Two levels of data , file name .

Group name : After the file is uploaded storage Group name , After the file is uploaded successfully storage Server return , It needs to be saved by the client .

Virtual disk path :storage Configured virtual path , With disk options store_path* Corresponding . If the

store_path0 It is M00, If the store_path1 It is M01, And so on .

Two levels of data :storage The two-level directory created by the server under each virtual disk path , For storing data

file .

file name : It's different from when the file is uploaded . Is generated by the storage server based on specific information , The filename contains : Source storage

The server IP Address 、 File creation timestamp 、 file size 、 Random numbers and file extensions .

1.2 FastDFS build

 

 

1.2.1 install FastDFS Mirror image

We use Docker build FastDFS Development environment of , The virtual machine has been downloaded fastdfs Mirror image , Can pass docker images see , Here's the picture :

Pull the mirror image ( The image has been downloaded , You don't need to download )

docker pull morunchang/fastdfs

function tracker

docker run -d --name tracker --net=host morunchang/fastdfs sh tracker.sh

function storage

docker run -d --name storage --net=host -e TRACKER_IP=192.168.211.132:22122 -e GROUP_NAME=group1 morunchang/fastdfs sh storage.sh
  • The network model used is –net=host, 192.168.211.132 It's the host computer IP
  • group1 Group name , namely storage Group
  • If you want to add new storage The server , Run the command again , Pay attention to replacement New group name

1.2.2 To configure Nginx

Nginx Here we mainly provide information about FastDFS Image access support ,Docker The container has been integrated with Nginx, We need to change nginx Configuration of , Get into storage Inside the container of , modify nginx.conf

docker exec -it storage  /bin/bash

After entering

vi /etc/nginx/conf/nginx.conf

Add the following

The configuration shown in the figure above is as follows :

1
2
3
4
location ~ /M00 {
     root /data/fast_data/data;
     ngx_fastdfs_module;
}

Disable caching :

add_header Cache-Control no-store;

Exit the container

exit

restart storage Containers

docker restart storage

Check the startup container docker ps

1
2
9f2391f73d97 morunchang/fastdfs "sh storage.sh" 12 minutes ago Up 12 seconds storage
e22a3c7f95ea morunchang/fastdfs "sh tracker.sh" 13 minutes ago Up 13 minutes tracker

Turn on startup settings

1
2
docker update --restart=always tracker
docker update --restart=always storage

1.3 File storage microservices

Create a file management microservice changgou-service-file, The project is mainly used to upload and delete files .

1.3.1 pom.xml rely on

modify pom.xml, Introduce dependencies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?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>changgou-service</artifactId>
        <groupId>com.changgou</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>changgou-service-file</artifactId>
    <description> File upload project </description>

    <!-- Dependency package -->
    <dependencies>
        <dependency>
            <groupId>net.oschina.zcx7878</groupId>
            <artifactId>fastdfs-client-java</artifactId>
            <version>1.27.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.changgou</groupId>
            <artifactId>changgou-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>

1.3.2 FastDFS To configure

stay resources Create under folder fasfDFS Configuration file for fdfs_client.conf

1
2
3
4
5
connect_timeout=60
network_timeout=60
charset=UTF-8
http.tracker_http_port=8080
tracker_server=192.168.211.132:22122

connect_timeout: Connection timeout , The unit is in seconds .

network_timeout: Communication timeout , The unit is in seconds . When sending or receiving data . Suppose you can't send or receive data after the timeout period , Then the network communication failed

charset: Character set

http.tracker_http_port :.tracker Of http port

tracker_server: tracker The server IP And port settings

1.3.3 application.yml To configure

stay resources Create under folder application.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
  application:
    name: file
server:
  port: 18082
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:7001/eureka
  instance:
    prefer-ip-address: true
feign:
  hystrix:
    enabled: true

max-file-size It's a single file size ,max-request-size Is to set the total upload data size

1.3.4 Start class

establish com.changgou package , Create startup class FileApplication

1
2
3
4
5
6
7
8
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@EnableEurekaClient
public class FileApplication {

    public static void main(String[] args) {
        SpringApplication.run(FileApplication.class);
    }
}

It's forbidden here DataSource Load and create .

1.4 Upload files

1.4.1 File information encapsulation

File upload usually has the name of the file 、 The content of the document 、 Extension of the file 、 Of documents md5 value 、 The author of the document, etc , We can create an object to encapsulate these properties , The code is as follows :

establish com.changgou.file.FastDFSFile The code is as follows :


public class FastDFSFile implements Serializable {

    // File name 
    private String name;
    // The contents of the document 
    private byte[] content;
    // File extension 
    private String ext;
    // file MD5 The summary is worth 
    private String md5;
    // The author of the document 
    private String author;

    public FastDFSFile(String name, byte[] content, String ext, String md5, String author) {
        this.name = name;
        this.content = content;
        this.ext = ext;
        this.md5 = md5;
        this.author = author;
    }

    public FastDFSFile(String name, byte[] content, String ext) {
        this.name = name;
        this.content = content;
        this.ext = ext;
    }

    public FastDFSFile() {
    }

    //..get..set..toString
}

( Optional ) Test file related operations :


package com.changgou.file.test;

import org.csource.fastdfs.*;
import org.junit.Test;

import java.io.*;
import java.net.InetSocketAddress;

/**
 *  describe 
 *
 * @author  Steamed buns from the Three Kingdoms 
 * @version 1.0
 * @package PACKAGE_NAME *
 * @since 1.0
 */

public class FastdfsClientTest {

    /**
     *  Upload files 
     *
     * @throws Exception
     */
    @Test
    public void upload() throws Exception {

        // Load the global configuration file 
        ClientGlobal.init("C:\\Users\\Administrator\\IdeaProjects\\beike\\changgou\\changgou-service\\changgou-service-file\\src\\main\\resources\\fdfs_client.conf");

        // establish TrackerClient Client object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient Object acquisition TrackerServer Information 
        TrackerServer trackerServer = trackerClient.getConnection();
        // obtain StorageClient object 
        StorageClient storageClient = new StorageClient(trackerServer, null);

        // Perform file upload 
        String[] jpgs = storageClient.upload_file("C:\\Users\\Administrator\\Pictures\\5b13cd6cN8e12d4aa.jpg", "jpg", null);

        for (String jpg : jpgs) {

            System.out.println(jpg);
        }

    }

    @Test
    public void delete() throws Exception {

        // Load the global configuration file 
        ClientGlobal.init("C:\\Users\\Administrator\\IdeaProjects\\beike\\changgou\\changgou-service\\changgou-service-file\\src\\main\\resources\\fdfs_client.conf");

        // establish TrackerClient Client object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient Object acquisition TrackerServer Information 
        TrackerServer trackerServer = trackerClient.getConnection();
        // obtain StorageClient object 
        StorageClient storageClient = new StorageClient(trackerServer, null);
        // Perform file upload 

        int group1 = storageClient.delete_file("group1", "M00/00/00/wKjThF1VEiyAJ0xzAANdC6JX9KA522.jpg");
        System.out.println(group1);
    }

    @Test
    public void download() throws Exception {

        // Load the global configuration file 
        ClientGlobal.init("C:\\Users\\Administrator\\IdeaProjects\\beike\\changgou\\changgou-service\\changgou-service-file\\src\\main\\resources\\fdfs_client.conf");

        // establish TrackerClient Client object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient Object acquisition TrackerServer Information 
        TrackerServer trackerServer = trackerClient.getConnection();
        // obtain StorageClient object 
        StorageClient storageClient = new StorageClient(trackerServer, null);
        // Perform file upload 
        byte[] bytes = storageClient.download_file("group1", "M00/00/00/wKjThF1VFfKAJRJDAANdC6JX9KA980.jpg");

        File file = new File("D:\\ceshi\\1234.jpg");

        FileOutputStream fileOutputStream = new FileOutputStream(file);

        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

        bufferedOutputStream.write(bytes);

        bufferedOutputStream.close();

        fileOutputStream.close();
    }

    // Get the information data of the file 
    @Test
    public void getFileInfo() throws Exception {
        // Load the global configuration file 
        ClientGlobal.init("C:\\Users\\Administrator\\IdeaProjects\\beike\\changgou\\changgou-service\\changgou-service-file\\src\\main\\resources\\fdfs_client.conf");

        // establish TrackerClient Client object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient Object acquisition TrackerServer Information 
        TrackerServer trackerServer = trackerClient.getConnection();
        // obtain StorageClient object 
        StorageClient storageClient = new StorageClient(trackerServer, null);
        // Perform file upload 

        FileInfo group1 = storageClient.get_file_info("group1", "M00/00/00/wKjThF1VFfKAJRJDAANdC6JX9KA980.jpg");

        System.out.println(group1);

    }

    // Get group related information 
    @Test
    public void getGroupInfo() throws Exception {
        // Load the global configuration file 
        ClientGlobal.init("C:\\Users\\Administrator\\IdeaProjects\\beike\\changgou\\changgou-service\\changgou-service-file\\src\\main\\resources\\fdfs_client.conf");

        // establish TrackerClient Client object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient Object acquisition TrackerServer Information 
        TrackerServer trackerServer = trackerClient.getConnection();

        StorageServer group1 = trackerClient.getStoreStorage(trackerServer, "group1");
        System.out.println(group1.getStorePathIndex());

        // The address of the server corresponding to the group    Because there may be multiple servers .
        ServerInfo[] group1s = trackerClient.getFetchStorages(trackerServer, "group1", "M00/00/00/wKjThF1VFfKAJRJDAANdC6JX9KA980.jpg");
        for (ServerInfo serverInfo : group1s) {
            System.out.println(serverInfo.getIpAddr());
            System.out.println(serverInfo.getPort());
        }
    }

    @Test
    public void getTrackerInfo() throws Exception {
        // Load the global configuration file 
        ClientGlobal.init("C:\\Users\\Administrator\\IdeaProjects\\beike\\changgou\\changgou-service\\changgou-service-file\\src\\main\\resources\\fdfs_client.conf");

        // establish TrackerClient Client object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient Object acquisition TrackerServer Information 
        TrackerServer trackerServer = trackerClient.getConnection();

        InetSocketAddress inetSocketAddress = trackerServer.getInetSocketAddress();
        System.out.println(inetSocketAddress);

    }


}

1.4.2 File operations

establish com.changgou.util.FastDFSClient class , Implement... In this class FastDFS Information acquisition and file related operations , The code is as follows :

(1) initialization Tracker Information

stay com.changgou.util.FastDFSClient Class Tracker Information , Add the following static blocks to the class :


/***
 *  initialization tracker Information 
 */
static {
    try {
        // obtain tracker Configuration file for fdfs_client.conf The location of 
        String filePath = new ClassPathResource("fdfs_client.conf").getPath();
        // load tracker Configuration information 
        ClientGlobal.init(filePath);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

(2) Upload files

Add the following methods to the class to realize file uploading :

 

 


32
/****
 *  Upload files 
 * @param file :  The file information to be uploaded is encapsulated ->FastDFSFile
 * @return String[]
 *          1: The group name stored in the file upload 
 *          2: File storage path 
 */
public static String[] upload(FastDFSFile file){
    // Get file author 
    NameValuePair[] meta_list = new NameValuePair[1];
    meta_list[0] =new NameValuePair(file.getAuthor());

    /***
     *  Return value after file upload 
     * uploadResults[0]: The group name stored in the file upload , for example :group1
     * uploadResults[1]: File storage path , for example :M00/00/00/wKjThF0DBzaAP23MAAXz2mMp9oM26.jpeg
     */
    String[] uploadResults = null;
    try {
        // establish TrackerClient Client object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient Object acquisition TrackerServer Information 
        TrackerServer trackerServer = trackerClient.getConnection();
        // obtain StorageClient object 
        StorageClient storageClient = new StorageClient(trackerServer, null);
        // Perform file upload 
        uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return uploadResults;
}

(3) Get file information

Add the following methods to the class to obtain file information :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/***
 *  Get file information 
 * @param groupName: Group name 
 * @param remoteFileName: File storage full name 
 */
public static FileInfo getFile(String groupName,String remoteFileName){
    try {
        // establish TrackerClient object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient get TrackerServer Information 
        TrackerServer trackerServer =trackerClient.getConnection();
        // adopt TrackerServer obtain StorageClient object 
        StorageClient storageClient = new StorageClient(trackerServer,null);
        // Get file information 
        return storageClient.get_file_info(groupName,remoteFileName);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

(4) File download

Add the following methods to the class to realize file download :


/***
 *  File download 
 * @param groupName: Group name 
 * @param remoteFileName: File storage full name 
 * @return
 */
public static InputStream downFile(String groupName,String remoteFileName){
    try {
        // establish TrackerClient object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient objects creating TrackerServer
        TrackerServer trackerServer = trackerClient.getConnection();
        // adopt TrackerServer establish StorageClient
        StorageClient storageClient = new StorageClient(trackerServer,null);
        // adopt StorageClient Download the file 
        byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
        // Convert byte array into byte input stream 
        return new ByteArrayInputStream(fileByte);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

(5) File deletion implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/***
 *  File deletion implementation 
 * @param groupName: Group name 
 * @param remoteFileName: File storage full name 
 */
public static void deleteFile(String groupName,String remoteFileName){
    try {
        // establish TrackerClient object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient obtain TrackerServer object 
        TrackerServer trackerServer = trackerClient.getConnection();
        // adopt TrackerServer establish StorageClient
        StorageClient storageClient = new StorageClient(trackerServer,null);
        // adopt StorageClient Delete file 
        storageClient.delete_file(groupName,remoteFileName);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

(6) Get group information

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/***
 *  Get group information 
 * @param groupName : Group name 
 */
public static StorageServer getStorages(String groupName){
    try {
        // establish TrackerClient object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient obtain TrackerServer object 
        TrackerServer trackerServer = trackerClient.getConnection();
        // adopt trackerClient obtain Storage Group information 
        return trackerClient.getStoreStorage(trackerServer,groupName);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

(7) According to the file group name and file storage path Storage Service IP、 Port information


16
17
18
/***
 *  According to the file group name and file storage path Storage Service IP、 Port information 
 * @param groupName : Group name 
 * @param remoteFileName : File storage full name 
 */
public static ServerInfo[] getServerInfo(String groupName, String remoteFileName){
    try {
        // establish TrackerClient object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient obtain TrackerServer object 
        TrackerServer trackerServer = trackerClient.getConnection();
        // Get service information 
        return trackerClient.getFetchStorages(trackerServer,groupName,remoteFileName);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

(8) obtain Tracker Service address

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/***
 *  obtain Tracker Service address 
 */
public static String getTrackerUrl(){
    try {
        // establish TrackerClient object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient obtain TrackerServer object 
        TrackerServer trackerServer = trackerClient.getConnection();
        // obtain Tracker Address 
        return "http://"+trackerServer.getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

(9) Optimize

We can find out , All of the above methods will involve getting TrackerServer perhaps StorageClient, We can extract them individually , Add the following to the class 2 A way :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/***
 *  obtain TrackerServer
 */
public static TrackerServer getTrackerServer() throws Exception{
    // establish TrackerClient object 
    TrackerClient trackerClient = new TrackerClient();
    // adopt TrackerClient obtain TrackerServer object 
    TrackerServer trackerServer = trackerClient.getConnection();
    return trackerServer;
}

/***
 *  obtain StorageClient
 * @return
 * @throws Exception
 */
public static StorageClient getStorageClient() throws Exception{
    // obtain TrackerServer
    TrackerServer trackerServer = getTrackerServer();
    // adopt TrackerServer establish StorageClient
    StorageClient storageClient = new StorageClient(trackerServer,null);
    return storageClient;
}

Modify other methods , In need of use TrackerServer and StorageClient When , Call the above method directly , The complete code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
public class FastDFSClient {

    /***
     *  initialization tracker Information 
     */
    static {
        try {
            // obtain tracker Configuration file for fdfs_client.conf The location of 
            String filePath = new ClassPathResource("fdfs_client.conf").getPath();
            // load tracker Configuration information 
            ClientGlobal.init(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /****
     *  Upload files 
     * @param file :  The file information to be uploaded is encapsulated ->FastDFSFile
     * @return String[]
     *          1: The group name stored in the file upload 
     *          2: File storage path 
     */
    public static String[] upload(FastDFSFile file){
        // Get file author 
        NameValuePair[] meta_list = new NameValuePair[1];
        meta_list[0] =new NameValuePair(file.getAuthor());

        /***
         *  Return value after file upload 
         * uploadResults[0]: The group name stored in the file upload , for example :group1
         * uploadResults[1]: File storage path , for example :M00/00/00/wKjThF0DBzaAP23MAAXz2mMp9oM26.jpeg
         */
        String[] uploadResults = null;
        try {
            // obtain StorageClient object 
            StorageClient storageClient = getStorageClient();
            // Perform file upload 
            uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uploadResults;
    }


    /***
     *  Get file information 
     * @param groupName: Group name 
     * @param remoteFileName: File storage full name 
     */
    public static FileInfo getFile(String groupName,String remoteFileName){
        try {
            // obtain StorageClient object 
            StorageClient storageClient = getStorageClient();
            // Get file information 
            return storageClient.get_file_info(groupName,remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     *  File download 
     * @param groupName: Group name 
     * @param remoteFileName: File storage full name 
     * @return
     */
    public static InputStream downFile(String groupName,String remoteFileName){
        try {
            // obtain StorageClient
            StorageClient storageClient = getStorageClient();
            // adopt StorageClient Download the file 
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            // Convert byte array into byte input stream 
            return new ByteArrayInputStream(fileByte);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     *  File deletion implementation 
     * @param groupName: Group name 
     * @param remoteFileName: File storage full name 
     */
    public static void deleteFile(String groupName,String remoteFileName){
        try {
            // obtain StorageClient
            StorageClient storageClient = getStorageClient();
            // adopt StorageClient Delete file 
            storageClient.delete_file(groupName,remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /***
     *  Get group information 
     * @param groupName : Group name 
     */
    public static StorageServer getStorages(String groupName){
        try {
            // establish TrackerClient object 
            TrackerClient trackerClient = new TrackerClient();
            // adopt TrackerClient obtain TrackerServer object 
            TrackerServer trackerServer = trackerClient.getConnection();
            // adopt trackerClient obtain Storage Group information 
            return trackerClient.getStoreStorage(trackerServer,groupName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     *  According to the file group name and file storage path Storage Service IP、 Port information 
     * @param groupName : Group name 
     * @param remoteFileName : File storage full name 
     */
    public static ServerInfo[] getServerInfo(String groupName, String remoteFileName){
        try {
            // establish TrackerClient object 
            TrackerClient trackerClient = new TrackerClient();
            // adopt TrackerClient obtain TrackerServer object 
            TrackerServer trackerServer = trackerClient.getConnection();
            // Get service information 
            return trackerClient.getFetchStorages(trackerServer,groupName,remoteFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     *  obtain Tracker Service address 
     */
    public static String getTrackerUrl(){
        try {
            // establish TrackerClient object 
            TrackerClient trackerClient = new TrackerClient();
            // adopt TrackerClient obtain TrackerServer object 
            TrackerServer trackerServer = trackerClient.getConnection();
            // obtain Tracker Address 
            return "http://"+trackerServer.getInetSocketAddress().getHostString()+":"+ClientGlobal.getG_tracker_http_port();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     *  obtain TrackerServer
     */
    public static TrackerServer getTrackerServer() throws Exception{
        // establish TrackerClient object 
        TrackerClient trackerClient = new TrackerClient();
        // adopt TrackerClient obtain TrackerServer object 
        TrackerServer trackerServer = trackerClient.getConnection();
        return trackerServer;
    }

    /***
     *  obtain StorageClient
     * @return
     * @throws Exception
     */
    public static StorageClient getStorageClient() throws Exception{
        // obtain TrackerServer
        TrackerServer trackerServer = getTrackerServer();
        // adopt TrackerServer establish StorageClient
        StorageClient storageClient = new StorageClient(trackerServer,null);
        return storageClient;
    }
}

1.4.3 Upload files

Create a FileController, In this controller, file upload operation is realized , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@RestController
@CrossOrigin
public class FileController {

    /***
     *  Upload files 
     * @return
     */
    @PostMapping(value = "/upload")
    public String upload(@RequestParam("file")MultipartFile file) throws Exception {
        // Encapsulates a FastDFSFile
        FastDFSFile fastDFSFile = new FastDFSFile(
                file.getOriginalFilename(), // File name 
                file.getBytes(),            // File byte array 
                StringUtils.getFilenameExtension(file.getOriginalFilename()));// File extension 

        // Upload files 
        String[] uploads = FastDFSClient.upload(fastDFSFile);
        // Assembly file upload address 
        return FastDFSClient.getTrackerUrl()+"/"+uploads[0]+"/"+uploads[1];
    }
}

1.5 Postman Test file upload

step :

1、 choice post Request mode , Enter the request address  http://localhost:18082/upload

2、 Fill in Headers

1
2
Key:Content-Type
Value:multipart/form-data

3、 Fill in body

choice form-data Then select the file file Click Add File , Send it at last .

visit http://192.168.211.132:8080/group1/M00/00/00/wKjThF0DBzaAP23MAAXz2mMp9oM26.jpeg Here's the picture

Be careful , The port accessed each time here is 8080 port , The access port is actually storage Container of nginx port , If you want to modify this port, you can directly enter storage Containers , Then modify it .

1
2
docker exec -it storage  /bin/bash
vi /etc/nginx/conf/nginx.conf

Restart after modification storage You can access the image according to your modified port .

2 Album management ( actual combat )

2.1 Demand analysis

Photo albums are snap INS for storing pictures , We usually upload the pictures of products to the album first , When adding items, you can directly select... From the album , Get the picture address in the album , Save to item table .

See the static prototype of the management background for the front-end interaction mode

2.2 Table structure analysis

tb_album surface (** albums **)

Field name Field meaning Field type remarks
id Number BIGINT(20) Primary key
title Album name VARCHAR(100) 
image Album cover VARCHAR(100) 
image_items Picture list TEXT 

In the table image_items The following example of data :

1
2
3
4
5
6
7
8
9
10
11
12
[
  {
    "url": "http://localhost:9101/img/1.jpg",
    "uid": 1548143143154,
    "status": "success"
  },
  {
    "url": "http://localhost:9101/img/7.jpg",
    "uid": 1548143143155,
    "status": "success"
  }
]

2.3 Code implementation

2.3.1 Pojo

stay changgou-service-goods-api Create in project com.changgou.goods.pojo.Album, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Table(name="tb_album")
public class Album implements Serializable{

	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
	private Long id;// Number 

    @Column(name = "title")
	private String title;// Album name 

    @Column(name = "image")
	private String image;// Album cover 

    @Column(name = "image_items")
	private String imageItems;// Picture list 

	//get...set...toString..
}

2.3.2 Dao

stay changgou-service-goods Created in com.changgou.goods.dao.AlbumMapper Interface , The code is as follows :

1
2
public interface AlbumMapper extends Mapper<Album> {
}

2.3.3 The business layer

(1) Business layer interface

stay changgou-service-goods Created in com.changgou.goods.service.AlbumService Interface , And add common methods , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public interface AlbumService {

    /***
     * Album Multi conditional paging query 
     * @param album
     * @param page
     * @param size
     * @return
     */
    PageInfo<Album> findPage(Album album, int page, int size);

    /***
     * Album Paging query 
     * @param page
     * @param size
     * @return
     */
    PageInfo<Album> findPage(int page, int size);

    /***
     * Album Multi criteria search method 
     * @param album
     * @return
     */
    List<Album> findList(Album album);

    /***
     *  Delete Album
     * @param id
     */
    void delete(Long id);

    /***
     *  modify Album data 
     * @param album
     */
    void update(Album album);

    /***
     *  newly added Album
     * @param album
     */
    void add(Album album);

    /**
     *  according to ID Inquire about Album
     * @param id
     * @return
     */
     Album findById(Long id);

    /***
     *  Query all Album
     * @return
     */
    List<Album> findAll();
}

(2) Business layer implementation classes

stay changgou-service-goods Created in com.changgou.goods.service.impl.AlbumServiceImpl, And implement the interface method , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@Service
public class AlbumServiceImpl implements AlbumService {

    @Autowired
    private AlbumMapper albumMapper;


    /**
     * Album Conditions + Paging query 
     * @param album  Query criteria 
     * @param page  Page number 
     * @param size  Page size 
     * @return  Paging results 
     */
    @Override
    public PageInfo<Album> findPage(Album album, int page, int size){
        // Pagination 
        PageHelper.startPage(page,size);
        // Search term construction 
        Example example = createExample(album);
        // Execution search 
        return new PageInfo<Album>(albumMapper.selectByExample(example));
    }

    /**
     * Album Paging query 
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Album> findPage(int page, int size){
        // Static paging 
        PageHelper.startPage(page,size);
        // Paging query 
        return new PageInfo<Album>(albumMapper.selectAll());
    }

    /**
     * Album Conditions of the query 
     * @param album
     * @return
     */
    @Override
    public List<Album> findList(Album album){
        // Build query criteria 
        Example example = createExample(album);
        // Query the data according to the constructed conditions 
        return albumMapper.selectByExample(example);
    }


    /**
     * Album Building query objects 
     * @param album
     * @return
     */
    public Example createExample(Album album){
        Example example=new Example(Album.class);
        Example.Criteria criteria = example.createCriteria();
        if(album!=null){
            //  Number 
            if(!StringUtils.isEmpty(album.getId())){
                    criteria.andEqualTo("id",album.getId());
            }
            //  Album name 
            if(!StringUtils.isEmpty(album.getTitle())){
                    criteria.andLike("title","%"+album.getTitle()+"%");
            }
            //  Album cover 
            if(!StringUtils.isEmpty(album.getImage())){
                    criteria.andEqualTo("image",album.getImage());
            }
            //  Picture list 
            if(!StringUtils.isEmpty(album.getImageItems())){
                    criteria.andEqualTo("imageItems",album.getImageItems());
            }
        }
        return example;
    }

    /**
     *  Delete 
     * @param id
     */
    @Override
    public void delete(Long id){
        albumMapper.deleteByPrimaryKey(id);
    }

    /**
     *  modify Album
     * @param album
     */
    @Override
    public void update(Album album){
        albumMapper.updateByPrimaryKey(album);
    }

    /**
     *  increase Album
     * @param album
     */
    @Override
    public void add(Album album){
        albumMapper.insert(album);
    }

    /**
     *  according to ID Inquire about Album
     * @param id
     * @return
     */
    @Override
    public Album findById(Long id){
        return  albumMapper.selectByPrimaryKey(id);
    }

    /**
     *  Inquire about Album All data 
     * @return
     */
    @Override
    public List<Album> findAll() {
        return albumMapper.selectAll();
    }
}

2.3.4 Control layer

stay changgou-service-service Create in project com.changgou.goods.controller.AlbumController, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
@RestController
@RequestMapping("/album")
@CrossOrigin
public class AlbumController {

    @Autowired
    private AlbumService albumService;

    /***
     * Album Paging condition search implementation 
     * @param album
     * @param page
     * @param size
     * @return
     */
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@RequestBody(required = false)  Album album, @PathVariable  int page, @PathVariable  int size){
        // Execution search 
        PageInfo<Album> pageInfo = albumService.findPage(album, page, size);
        return new Result(true,StatusCode.OK," The query is successful ",pageInfo);
    }

    /***
     * Album Paging search implementation 
     * @param page: The current page 
     * @param size: How many items are displayed per page 
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@PathVariable  int page, @PathVariable  int size){
        // Paging query 
        PageInfo<Album> pageInfo = albumService.findPage(page, size);
        return new Result<PageInfo>(true,StatusCode.OK," The query is successful ",pageInfo);
    }

    /***
     *  Multi criteria search for brand data 
     * @param album
     * @return
     */
    @PostMapping(value = "/search" )
    public Result<List<Album>> findList(@RequestBody(required = false)  Album album){
        List<Album> list = albumService.findList(album);
        return new Result<List<Album>>(true,StatusCode.OK," The query is successful ",list);
    }

    /***
     *  according to ID Delete brand data 
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable Long id){
        albumService.delete(id);
        return new Result(true,StatusCode.OK," Delete successful ");
    }

    /***
     *  modify Album data 
     * @param album
     * @param id
     * @return
     */
    @PutMapping(value="/{id}")
    public Result update(@RequestBody  Album album,@PathVariable Long id){
        // Set primary key value 
        album.setId(id);
        // Modifying data 
        albumService.update(album);
        return new Result(true,StatusCode.OK," Modification successful ");
    }

    /***
     *  newly added Album data 
     * @param album
     * @return
     */
    @PostMapping
    public Result add(@RequestBody   Album album){
        albumService.add(album);
        return new Result(true,StatusCode.OK," Add success ");
    }

    /***
     *  according to ID Inquire about Album data 
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Album> findById(@PathVariable Long id){
        // according to ID Inquire about 
        Album album = albumService.findById(id);
        return new Result<Album>(true,StatusCode.OK," The query is successful ",album);
    }

    /***
     *  Inquire about Album All data 
     * @return
     */
    @GetMapping
    public Result<Album> findAll(){
        List<Album> list = albumService.findAll();
        return new Result<Album>(true, StatusCode.OK," The query is successful ",list) ;
    }
}

3 Specification parameter template ( actual combat )

3.1 Demand analysis

A specification parameter template is a unit for managing specification parameters . Specifications are, for example, color 、 Mobile phone running memory and other information , Parameters are, for example, system : Android (Android) Rear camera pixels :2000 Million or more hotspot : Fast charging and other information .

See the static prototype of the management background for the front-end interaction mode

3.2 Table structure analysis

The tables related to the specification parameter template are 3 individual

tb_template surface ( Template table )

Field name Field meaning Field type Field length remarks
idIDINT  
name Template name VARCHAR  
spec_num Specification and quantity INT  
para_num The number of arguments INT  

tb_spec surface ( Specification sheet )

Field name Field meaning Field type Field length remarks
idIDINT  
name name VARCHAR  
options Specification options VARCHAR  
seq Sort INT  
template_id Templates IDINT  

tb_para surface ( Parameter table )

Field name Field meaning Field type Field length remarks
ididINT  
name name VARCHAR  
options Options VARCHAR  
seq Sort INT  
template_id Templates IDINT  

The relationship between template and specification is one to many , Templates and parameters have a one to many relationship

3.3 Template Management

3.3.1 Pojo

stay changgou-service-goods-api Create in project com.changgou.goods.pojo.Template, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Table(name="tb_template")
public class Template implements Serializable{

	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
	private Integer id;//ID

    @Column(name = "name")
	private String name;// Template name 

    @Column(name = "spec_num")
	private Integer specNum;// Specification and quantity 

    @Column(name = "para_num")
	private Integer paraNum;// The number of arguments 
	//..get..set..toString
}

3.3.2 Dao

stay changgou-service-goods Created in com.changgou.goods.dao.TemplateMapper, The code is as follows :

1
2
public interface TemplateMapper extends Mapper<Template> {
}

3.3.3 The business layer

(1) Business layer interface

stay changgou-service-goods Created in com.changgou.goods.service.TemplateService Interface , And add related methods , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public interface TemplateService {

    /***
     * Template Multi conditional paging query 
     * @param template
     * @param page
     * @param size
     * @return
     */
    PageInfo<Template> findPage(Template template, int page, int size);

    /***
     * Template Paging query 
     * @param page
     * @param size
     * @return
     */
    PageInfo<Template> findPage(int page, int size);

    /***
     * Template Multi criteria search method 
     * @param template
     * @return
     */
    List<Template> findList(Template template);

    /***
     *  Delete Template
     * @param id
     */
    void delete(Integer id);

    /***
     *  modify Template data 
     * @param template
     */
    void update(Template template);

    /***
     *  newly added Template
     * @param template
     */
    void add(Template template);

    /**
     *  according to ID Inquire about Template
     * @param id
     * @return
     */
     Template findById(Integer id);

    /***
     *  Query all Template
     * @return
     */
    List<Template> findAll();
}

(2) Business layer interface implementation class

stay changgou-service-goods Created in com.changgou.goods.service.impl.TemplateServiceImpl Implementation class , And implement the corresponding method , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@Service
public class TemplateServiceImpl implements TemplateService {

    @Autowired
    private TemplateMapper templateMapper;


    /**
     * Template Conditions + Paging query 
     * @param template  Query criteria 
     * @param page  Page number 
     * @param size  Page size 
     * @return  Paging results 
     */
    @Override
    public PageInfo<Template> findPage(Template template, int page, int size){
        // Pagination 
        PageHelper.startPage(page,size);
        // Search term construction 
        Example example = createExample(template);
        // Execution search 
        return new PageInfo<Template>(templateMapper.selectByExample(example));
    }

    /**
     * Template Paging query 
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Template> findPage(int page, int size){
        // Static paging 
        PageHelper.startPage(page,size);
        // Paging query 
        return new PageInfo<Template>(templateMapper.selectAll());
    }

    /**
     * Template Conditions of the query 
     * @param template
     * @return
     */
    @Override
    public List<Template> findList(Template template){
        // Build query criteria 
        Example example = createExample(template);
        // Query the data according to the constructed conditions 
        return templateMapper.selectByExample(example);
    }


    /**
     * Template Building query objects 
     * @param template
     * @return
     */
    public Example createExample(Template template){
        Example example=new Example(Template.class);
        Example.Criteria criteria = example.createCriteria();
        if(template!=null){
            // ID
            if(!StringUtils.isEmpty(template.getId())){
                    criteria.andEqualTo("id",template.getId());
            }
            //  Template name 
            if(!StringUtils.isEmpty(template.getName())){
                    criteria.andLike("name","%"+template.getName()+"%");
            }
            //  Specification and quantity 
            if(!StringUtils.isEmpty(template.getSpecNum())){
                    criteria.andEqualTo("specNum",template.getSpecNum());
            }
            //  The number of arguments 
            if(!StringUtils.isEmpty(template.getParaNum())){
                    criteria.andEqualTo("paraNum",template.getParaNum());
            }
        }
        return example;
    }

    /**
     *  Delete 
     * @param id
     */
    @Override
    public void delete(Integer id){
        templateMapper.deleteByPrimaryKey(id);
    }

    /**
     *  modify Template
     * @param template
     */
    @Override
    public void update(Template template){
        templateMapper.updateByPrimaryKey(template);
    }

    /**
     *  increase Template
     * @param template
     */
    @Override
    public void add(Template template){
        templateMapper.insert(template);
    }

    /**
     *  according to ID Inquire about Template
     * @param id
     * @return
     */
    @Override
    public Template findById(Integer id){
        return  templateMapper.selectByPrimaryKey(id);
    }

    /**
     *  Inquire about Template All data 
     * @return
     */
    @Override
    public List<Template> findAll() {
        return templateMapper.selectAll();
    }
}

3.3.4 Control layer

stay changgou-service-goods Created in com.changgou.goods.controller.TemplateController, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
@RestController
@RequestMapping("/template")
@CrossOrigin
public class TemplateController {

    @Autowired
    private TemplateService templateService;

    /***
     * Template Paging condition search implementation 
     * @param template
     * @param page
     * @param size
     * @return
     */
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@RequestBody(required = false)  Template template, @PathVariable  int page, @PathVariable  int size){
        // Execution search 
        PageInfo<Template> pageInfo = templateService.findPage(template, page, size);
        return new Result(true,StatusCode.OK," The query is successful ",pageInfo);
    }

    /***
     * Template Paging search implementation 
     * @param page: The current page 
     * @param size: How many items are displayed per page 
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@PathVariable  int page, @PathVariable  int size){
        // Paging query 
        PageInfo<Template> pageInfo = templateService.findPage(page, size);
        return new Result<PageInfo>(true,StatusCode.OK," The query is successful ",pageInfo);
    }

    /***
     *  Multi criteria search for brand data 
     * @param template
     * @return
     */
    @PostMapping(value = "/search" )
    public Result<List<Template>> findList(@RequestBody(required = false)  Template template){
        List<Template> list = templateService.findList(template);
        return new Result<List<Template>>(true,StatusCode.OK," The query is successful ",list);
    }

    /***
     *  according to ID Delete brand data 
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable Integer id){
        templateService.delete(id);
        return new Result(true,StatusCode.OK," Delete successful ");
    }

    /***
     *  modify Template data 
     * @param template
     * @param id
     * @return
     */
    @PutMapping(value="/{id}")
    public Result update(@RequestBody  Template template,@PathVariable Integer id){
        // Set primary key value 
        template.setId(id);
        // Modifying data 
        templateService.update(template);
        return new Result(true,StatusCode.OK," Modification successful ");
    }

    /***
     *  newly added Template data 
     * @param template
     * @return
     */
    @PostMapping
    public Result add(@RequestBody   Template template){
        templateService.add(template);
        return new Result(true,StatusCode.OK," Add success ");
    }

    /***
     *  according to ID Inquire about Template data 
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Template> findById(@PathVariable Integer id){
        // according to ID Inquire about 
        Template template = templateService.findById(id);
        return new Result<Template>(true,StatusCode.OK," The query is successful ",template);
    }

    /***
     *  Inquire about Template All data 
     * @return
     */
    @GetMapping
    public Result<Template> findAll(){
        List<Template> list = templateService.findAll();
        return new Result<Template>(true, StatusCode.OK," The query is successful ",list) ;
    }
}

3.4 Specification Management

3.4.1 Pojo

stay changgou-service-goods-api Created in com.changgou.goods.pojo.Spec, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Table(name="tb_spec")
public class Spec implements Serializable{

	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
	private Integer id;//ID

    @Column(name = "name")
	private String name;// name 

    @Column(name = "options")
	private String options;// Specification options 

    @Column(name = "seq")
	private Integer seq;// Sort 

    @Column(name = "template_id")
	private Integer templateId;// Templates ID
	
	//get..set..toString
}

3.4.2 Dao

stay changgou-service-goods Created in com.changgou.goods.dao.SpecMapper, The code is as follows :

1
2
public interface SpecMapper extends Mapper<Spec> {
}

3.4.3 The business layer

(1) Business layer interface

stay changgou-service-goods Created in com.changgou.goods.service.SpecService Interface , And implement the corresponding method , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public interface SpecService {

    /***
     * Spec Multi conditional paging query 
     * @param spec
     * @param page
     * @param size
     * @return
     */
    PageInfo<Spec> findPage(Spec spec, int page, int size);

    /***
     * Spec Paging query 
     * @param page
     * @param size
     * @return
     */
    PageInfo<Spec> findPage(int page, int size);

    /***
     * Spec Multi criteria search method 
     * @param spec
     * @return
     */
    List<Spec> findList(Spec spec);

    /***
     *  Delete Spec
     * @param id
     */
    void delete(Integer id);

    /***
     *  modify Spec data 
     * @param spec
     */
    void update(Spec spec);

    /***
     *  newly added Spec
     * @param spec
     */
    void add(Spec spec);

    /**
     *  according to ID Inquire about Spec
     * @param id
     * @return
     */
     Spec findById(Integer id);

    /***
     *  Query all Spec
     * @return
     */
    List<Spec> findAll();
}

(2) Business layer implementation classes

stay changgou-service-goods Created in com.changgou.goods.service.impl.SpecServiceImpl, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
@Service
public class SpecServiceImpl implements SpecService {

    @Autowired
    private SpecMapper specMapper;

    @Autowired
    private TemplateMapper templateMapper;

    /**
     * Spec Conditions + Paging query 
     * @param spec  Query criteria 
     * @param page  Page number 
     * @param size  Page size 
     * @return  Paging results 
     */
    @Override
    public PageInfo<Spec> findPage(Spec spec, int page, int size){
        // Pagination 
        PageHelper.startPage(page,size);
        // Search term construction 
        Example example = createExample(spec);
        // Execution search 
        return new PageInfo<Spec>(specMapper.selectByExample(example));
    }

    /**
     * Spec Paging query 
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Spec> findPage(int page, int size){
        // Static paging 
        PageHelper.startPage(page,size);
        // Paging query 
        return new PageInfo<Spec>(specMapper.selectAll());
    }

    /**
     * Spec Conditions of the query 
     * @param spec
     * @return
     */
    @Override
    public List<Spec> findList(Spec spec){
        // Build query criteria 
        Example example = createExample(spec);
        // Query the data according to the constructed conditions 
        return specMapper.selectByExample(example);
    }


    /**
     * Spec Building query objects 
     * @param spec
     * @return
     */
    public Example createExample(Spec spec){
        Example example=new Example(Spec.class);
        Example.Criteria criteria = example.createCriteria();
        if(spec!=null){
            // ID
            if(!StringUtils.isEmpty(spec.getId())){
                    criteria.andEqualTo("id",spec.getId());
            }
            //  name 
            if(!StringUtils.isEmpty(spec.getName())){
                    criteria.andLike("name","%"+spec.getName()+"%");
            }
            //  Specification options 
            if(!StringUtils.isEmpty(spec.getOptions())){
                    criteria.andEqualTo("options",spec.getOptions());
            }
            //  Sort 
            if(!StringUtils.isEmpty(spec.getSeq())){
                    criteria.andEqualTo("seq",spec.getSeq());
            }
            //  Templates ID
            if(!StringUtils.isEmpty(spec.getTemplateId())){
                    criteria.andEqualTo("templateId",spec.getTemplateId());
            }
        }
        return example;
    }

    /**
     *  Delete 
     * @param id
     */
    @Override
    public void delete(Integer id){
        // Query template 
        Spec spec = specMapper.selectByPrimaryKey(id);
        // Change the number of templates 
        updateSpecNum(spec,-1);

        // Delete the specified specification 
        specMapper.deleteByPrimaryKey(id);
    }

    /**
     *  modify Spec
     * @param spec
     */
    @Override
    public void update(Spec spec){
        specMapper.updateByPrimaryKey(spec);
    }

    /**
     *  increase Spec
     * @param spec
     */
    @Override
    public void add(Spec spec){
        specMapper.insert(spec);
        // Change the number of templates 
        updateSpecNum(spec,1);
    }

    /**
     *  according to ID Inquire about Spec
     * @param id
     * @return
     */
    @Override
    public Spec findById(Integer id){
        return  specMapper.selectByPrimaryKey(id);
    }

    /**
     *  Inquire about Spec All data 
     * @return
     */
    @Override
    public List<Spec> findAll() {
        return specMapper.selectAll();
    }


    /**
     *  Modify template statistics 
     * @param spec: Operation template 
     * @param count: The number of changes 
     */
    public void updateSpecNum(Spec spec,int count){
        // Modify template quantity statistics 
        Template template = templateMapper.selectByPrimaryKey(spec.getTemplateId());
        template.setSpecNum(template.getSpecNum()+count);
        templateMapper.updateByPrimaryKeySelective(template);
    }
}

Note here , Every time you add or delete , The template needs to be called , Modify Statistics , In addition, let's think about , If it is a modification , Will the template statistics be changed ?

3.4.4 Control layer

stay changgou-service-goods Created in com.changgou.goods.controller.SpecController, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
@RestController
@RequestMapping("/spec")
@CrossOrigin
public class SpecController {

    @Autowired
    private SpecService specService;

    /***
     * Spec Paging condition search implementation 
     * @param spec
     * @param page
     * @param size
     * @return
     */
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@RequestBody(required = false)  Spec spec, @PathVariable  int page, @PathVariable  int size){
        // Execution search 
        PageInfo<Spec> pageInfo = specService.findPage(spec, page, size);
        return new Result(true,StatusCode.OK," The query is successful ",pageInfo);
    }

    /***
     * Spec Paging search implementation 
     * @param page: The current page 
     * @param size: How many items are displayed per page 
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@PathVariable  int page, @PathVariable  int size){
        // Paging query 
        PageInfo<Spec> pageInfo = specService.findPage(page, size);
        return new Result<PageInfo>(true,StatusCode.OK," The query is successful ",pageInfo);
    }

    /***
     *  Multi criteria search for brand data 
     * @param spec
     * @return
     */
    @PostMapping(value = "/search" )
    public Result<List<Spec>> findList(@RequestBody(required = false)  Spec spec){
        List<Spec> list = specService.findList(spec);
        return new Result<List<Spec>>(true,StatusCode.OK," The query is successful ",list);
    }

    /***
     *  according to ID Delete brand data 
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable Integer id){
        specService.delete(id);
        return new Result(true,StatusCode.OK," Delete successful ");
    }

    /***
     *  modify Spec data 
     * @param spec
     * @param id
     * @return
     */
    @PutMapping(value="/{id}")
    public Result update(@RequestBody  Spec spec,@PathVariable Integer id){
        // Set primary key value 
        spec.setId(id);
        // Modifying data 
        specService.update(spec);
        return new Result(true,StatusCode.OK," Modification successful ");
    }

    /***
     *  newly added Spec data 
     * @param spec
     * @return
     */
    @PostMapping
    public Result add(@RequestBody   Spec spec){
        specService.add(spec);
        return new Result(true,StatusCode.OK," Add success ");
    }

    /***
     *  according to ID Inquire about Spec data 
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Spec> findById(@PathVariable Integer id){
        // according to ID Inquire about 
        Spec spec = specService.findById(id);
        return new Result<Spec>(true,StatusCode.OK," The query is successful ",spec);
    }

    /***
     *  Inquire about Spec All data 
     * @return
     */
    @GetMapping
    public Result<Spec> findAll(){
        List<Spec> list = specService.findAll();
        return new Result<Spec>(true, StatusCode.OK," The query is successful ",list) ;
    }
}

3.5 Parameter management

3.5.1 Pojo

stay changgou-service-goods-api Created in com.changgou.goods.pojo.Para, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Table(name="tb_para")
public class Para implements Serializable{

	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
	private Integer id;//id

    @Column(name = "name")
	private String name;// name 

    @Column(name = "options")
	private String options;// Options 

    @Column(name = "seq")
	private Integer seq;// Sort 

    @Column(name = "template_id")
	private Integer templateId;// Templates ID
	//get..set..toString
}

3.5.2 Dao

stay changgou-service-goods Created in com.changgou.goods.dao.ParaMapper, The code is as follows :

1
2
public interface ParaMapper extends Mapper<Para> {
}

3.5.3 The business layer

(1) Business layer interface

stay changgou-service-goods Created in com.changgou.goods.service.ParaService Interface , And add common methods , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public interface ParaService {

    /***
     * Para Multi conditional paging query 
     * @param para
     * @param page
     * @param size
     * @return
     */
    PageInfo<Para> findPage(Para para, int page, int size);

    /***
     * Para Paging query 
     * @param page
     * @param size
     * @return
     */
    PageInfo<Para> findPage(int page, int size);

    /***
     * Para Multi criteria search method 
     * @param para
     * @return
     */
    List<Para> findList(Para para);

    /***
     *  Delete Para
     * @param id
     */
    void delete(Integer id);

    /***
     *  modify Para data 
     * @param para
     */
    void update(Para para);

    /***
     *  newly added Para
     * @param para
     */
    void add(Para para);

    /**
     *  according to ID Inquire about Para
     * @param id
     * @return
     */
    Para findById(Integer id);

    /***
     *  Query all Para
     * @return
     */
    List<Para> findAll();
}

(2) Business layer interface implementation class

stay changgou-service-goods Created in com.changgou.goods.service.impl.ParaServiceImpl Interface implementation class , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
@Service
public class ParaServiceImpl implements ParaService {

    @Autowired
    private ParaMapper paraMapper;

    @Autowired
    private TemplateMapper templateMapper;

    /**
     * Para Conditions + Paging query 
     * @param para  Query criteria 
     * @param page  Page number 
     * @param size  Page size 
     * @return  Paging results 
     */
    @Override
    public PageInfo<Para> findPage(Para para, int page, int size){
        // Pagination 
        PageHelper.startPage(page,size);
        // Search term construction 
        Example example = createExample(para);
        // Execution search 
        return new PageInfo<Para>(paraMapper.selectByExample(example));
    }

    /**
     * Para Paging query 
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Para> findPage(int page, int size){
        // Static paging 
        PageHelper.startPage(page,size);
        // Paging query 
        return new PageInfo<Para>(paraMapper.selectAll());
    }

    /**
     * Para Conditions of the query 
     * @param para
     * @return
     */
    @Override
    public List<Para> findList(Para para){
        // Build query criteria 
        Example example = createExample(para);
        // Query the data according to the constructed conditions 
        return paraMapper.selectByExample(example);
    }


    /**
     * Para Building query objects 
     * @param para
     * @return
     */
    public Example createExample(Para para){
        Example example=new Example(Para.class);
        Example.Criteria criteria = example.createCriteria();
        if(para!=null){
            // id
            if(!StringUtils.isEmpty(para.getId())){
                    criteria.andEqualTo("id",para.getId());
            }
            //  name 
            if(!StringUtils.isEmpty(para.getName())){
                    criteria.andLike("name","%"+para.getName()+"%");
            }
            //  Options 
            if(!StringUtils.isEmpty(para.getOptions())){
                    criteria.andEqualTo("options",para.getOptions());
            }
            //  Sort 
            if(!StringUtils.isEmpty(para.getSeq())){
                    criteria.andEqualTo("seq",para.getSeq());
            }
            //  Templates ID
            if(!StringUtils.isEmpty(para.getTemplateId())){
                    criteria.andEqualTo("templateId",para.getTemplateId());
            }
        }
        return example;
    }

    /**
     *  Delete 
     * @param id
     */
    @Override
    public void delete(Integer id){
        // according to ID Inquire about 
        Para para = paraMapper.selectByPrimaryKey(id);
        // Modify template statistics 
        updateParaNum(para,-1);

        paraMapper.deleteByPrimaryKey(id);
    }

    /**
     *  modify Para
     * @param para
     */
    @Override
    public void update(Para para){
        paraMapper.updateByPrimaryKey(para);
    }

    /**
     *  increase Para
     * @param para
     */
    @Override
    public void add(Para para){
        paraMapper.insert(para);

        // Modify template statistics 
        updateParaNum(para,1);
    }

    /**
     *  according to ID Inquire about Para
     * @param id
     * @return
     */
    @Override
    public Para findById(Integer id){
        return  paraMapper.selectByPrimaryKey(id);
    }

    /**
     *  Inquire about Para All data 
     * @return
     */
    @Override
    public List<Para> findAll() {
        return paraMapper.selectAll();
    }

    /**
     *  Modify template statistics 
     * @param para: Parameters of operation 
     * @param count: The number of changes 
     */
    public void updateParaNum(Para para, int count){
        // Modify template quantity statistics 
        Template template = templateMapper.selectByPrimaryKey(para.getTemplateId());
        template.setParaNum(template.getParaNum()+count);
        templateMapper.updateByPrimaryKeySelective(template);
    }
}

3.5.4 Control layer

stay changgou-service-goods Create com.changgou.goods.controller.ParaController, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
@RestController
@RequestMapping("/para")
@CrossOrigin
public class ParaController {

    @Autowired
    private ParaService paraService;

    /***
     * Para Paging condition search implementation 
     * @param para
     * @param page
     * @param size
     * @return
     */
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@RequestBody(required = false)  Para para, @PathVariable  int page, @PathVariable  int size){
        // Execution search 
        PageInfo<Para> pageInfo = paraService.findPage(para, page, size);
        return new Result(true,StatusCode.OK," The query is successful ",pageInfo);
    }

    /***
     * Para Paging search implementation 
     * @param page: The current page 
     * @param size: How many items are displayed per page 
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@PathVariable  int page, @PathVariable  int size){
        // Paging query 
        PageInfo<Para> pageInfo = paraService.findPage(page, size);
        return new Result<PageInfo>(true,StatusCode.OK," The query is successful ",pageInfo);
    }

    /***
     *  Multi criteria search for brand data 
     * @param para
     * @return
     */
    @PostMapping(value = "/search" )
    public Result<List<Para>> findList(@RequestBody(required = false)  Para para){
        List<Para> list = paraService.findList(para);
        return new Result<List<Para>>(true,StatusCode.OK," The query is successful ",list);
    }

    /***
     *  according to ID Delete brand data 
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable Integer id){
        paraService.delete(id);
        return new Result(true,StatusCode.OK," Delete successful ");
    }

    /***
     *  modify Para data 
     * @param para
     * @param id
     * @return
     */
    @PutMapping(value="/{id}")
    public Result update(@RequestBody  Para para,@PathVariable Integer id){
        // Set primary key value 
        para.setId(id);
        // Modifying data 
        paraService.update(para);
        return new Result(true,StatusCode.OK," Modification successful ");
    }

    /***
     *  newly added Para data 
     * @param para
     * @return
     */
    @PostMapping
    public Result add(@RequestBody   Para para){
        paraService.add(para);
        return new Result(true,StatusCode.OK," Add success ");
    }

    /***
     *  according to ID Inquire about Para data 
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Para> findById(@PathVariable Integer id){
        // according to ID Inquire about 
        Para para = paraService.findById(id);
        return new Result<Para>(true,StatusCode.OK," The query is successful ",para);
    }

    /***
     *  Inquire about Para All data 
     * @return
     */
    @GetMapping
    public Result<Para> findAll(){
        List<Para> list = paraService.findAll();
        return new Result<Para>(true, StatusCode.OK," The query is successful ",list) ;
    }
}

4 Classification of goods ( actual combat )

4.1 Demand analysis

Commodity classification is divided into three levels of management , The main function is to display the product navigation in the home page of the website , And when managing the commodities in the background .

See the static prototype of the management background for the front-end interaction mode

4.2 Table structure analysis

tb_category surface (** Classification of goods **)

Field name Field meaning Field type Field length remarks
id classification IDINT  
name Category name VARCHAR  
goods_num The number INT  
is_show Whether or not shown CHAR 0 No display 1 Show
is_menu Navigation or not CHAR 0 Navigation from time to time 1 For navigation
seq Sort INT  
parent_id The superior IDINT  
template_id Templates IDINT  

Commodity classification and template are many to one

4.3 Realization

4.3.1 Pojo

stay changgou-service-goods-api Created in com.changgou.goods.pojo.Category, The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Table(name="tb_category")
public class Category implements Serializable{

	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
	private Integer id;// classification ID

    @Column(name = "name")
	private String name;// Category name 

    @Column(name = "goods_num")
	private Integer goodsNum;// The number 

    @Column(name = "is_show")
	private String isShow;// Whether or not shown 

    @Column(name = "is_menu")
	private String isMenu;// Navigation or not 

    @Column(name = "seq")
	private Integer seq;// Sort 

    @Column(name = "parent_id")
	private Integer parentId;// The superior ID

    @Column(name = "template_id")
	private Integer templateId;// Templates ID
	//..set..get..toString
}

4.3.2 Dao

stay changgou-servicegoods Created in com.changgou.goods.dao.CategoryMapper Interface , The code is as follows :

1
2
public interface CategoryMapper extends Mapper<Category> {
}

4.3.3 The business layer

(1) Business layer interface

modify changgou-service-goods, add to com.changgou.goods.service.CategoryService Interface , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public interface CategoryService {

    /***
     * Category Multi conditional paging query 
     * @param category
     * @param page
     * @param size
     * @return
     */
    PageInfo<Category> findPage(Category category, int page, int size);

    /***
     * Category Paging query 
     * @param page
     * @param size
     * @return
     */
    PageInfo<Category> findPage(int page, int size);

    /***
     * Category Multi criteria search method 
     * @param category
     * @return
     */
    List<Category> findList(Category category);

    /***
     *  Delete Category
     * @param id
     */
    void delete(Integer id);

    /***
     *  modify Category data 
     * @param category
     */
    void update(Category category);

    /***
     *  newly added Category
     * @param category
     */
    void add(Category category);

    /**
     *  according to ID Inquire about Category
     * @param id
     * @return
     */
     Category findById(Integer id);

    /***
     *  Query all Category
     * @return
     */
    List<Category> findAll();

    /***
     *  According to the parent node ID Inquire about 
     * @param pid: Parent node ID
     */
    List<Category> findByParentId(Integer pid);
}

(2) Business layer interface implementation class

modify changgou-service-goods, add to com.changgou.goods.service.impl.CategoryServiceImpl Interface implementation class , The code is as follows :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    /**
     * Category Conditions + Paging query 
     * @param category  Query criteria 
     * @param page  Page number 
     * @param size  Page size 
     * @return  Paging results 
     */
    @Override
    public PageInfo<Category> findPage(Category category, int page, int size){
        // Pagination 
        PageHelper.startPage(page,size);
        // Search term construction 
        Example example = createExample(category);
        // Execution search 
        return new PageInfo<Category>(categoryMapper.selectByExample(example));
    }

    /**
     * Category Paging query 
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<Category> findPage(int page, int size){
        // Static paging 
        PageHelper.startPage(page,size);
        // Paging query 
        return new PageInfo<Category>(categoryMapper.selectAll());
    }

    /**
     * Category Conditions of the query 
     * @param category
     * @return
     */
    @Override
    public List<Category> findList(Category category){
        // Build query criteria 
        Example example = createExample(category);
        // Query the data according to the constructed conditions 
        return categoryMapper.selectByExample(example);
    }


    /**
     * Category Building query objects 
     * @param category
     * @return
     */
    public Example createExample(Category category){
        Example example=new Example(Category.class);
        Example.Criteria criteria = example.createCriteria();
        if(category!=null){
            //  classification ID
            if(!StringUtils.isEmpty(category.getId())){
                    criteria.andEqualTo("id",category.getId());
            }
            //  Category name 
            if(!StringUtils.isEmpty(category.getName())){
                    criteria.andLike("name","%"+category.getName()+"%");
            }
            //  The number 
            if(!StringUtils.isEmpty(category.getGoodsNum())){
                    criteria.andEqualTo("goodsNum",category.getGoodsNum());
            }
            //  Whether or not shown 
            if(!StringUtils.isEmpty(category.getIsShow())){
                    criteria.andEqualTo("isShow",category.getIsShow());
            }
            //  Navigation or not 
            if(!StringUtils.isEmpty(category.getIsMenu())){
                    criteria.andEqualTo("isMenu",category.getIsMenu());
            }
            //  Sort 
            if(!StringUtils.isEmpty(category.getSeq())){
                    criteria.andEqualTo("seq",category.getSeq());
            }
            //  The superior ID
            if(!StringUtils.isEmpty(category.getParentId())){
                    criteria.andEqualTo("parentId",category.getParentId());
            }
            //  Templates ID
            if(!StringUtils.isEmpty(category.getTemplateId())){
                    criteria.andEqualTo("templateId",category.getTemplateId());
            }
        }
        return example;
    }

    /**
     *  Delete 
     * @param id
     */
    @Override
    public void delete(Integer id){
        categoryMapper.deleteByPrimaryKey(id);
    }

    /**
     *  modify Category
     * @param category
     */
    @Override
    public void update(Category category){
        categoryMapper.updateByPrimaryKey(category);
    }

    /**
     *  increase Category
     * @param category
     */
    @Override
    public void add(Category category){
        categoryMapper.insert(category);
    }

    /**
     *  according to ID Inquire about Category
     * @param id
     * @return
     */
    @Override
    public Category findById(Integer id){
        return  categoryMapper.selectByPrimaryKey(id);
    }

    /**
     *  Inquire about Category All data 
     * @return
     */
    @Override
    public List<Category> findAll() {
        return categoryMapper.selectAll();
    }

    /***
     *  According to the parent node ID Inquire about 
     * @param pid: Parent node ID
     */
    @Override
    public List<Category> findByParentId(Integer pid) {
        Category category = new Category();
        category.setParentId(pid);
        return categoryMapper.select(category);
    }
}

4.3.4 Control layer

modify changgou-service-goods, add to com.changgou.goods.controller.CategoryController, The code is as follows :


@RestController
@RequestMapping("/category")
@CrossOrigin
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /***
     * Category Paging condition search implementation 
     * @param category
     * @param page
     * @param size
     * @return
     */
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@RequestBody(required = false)  Category category, @PathVariable  int page, @PathVariable  int size){
        // Execution search 
        PageInfo<Category> pageInfo = categoryService.findPage(category, page, size);
        return new Result(true,StatusCode.OK," The query is successful ",pageInfo);
    }

    /***
     * Category Paging search implementation 
     * @param page: The current page 
     * @param size: How many items are displayed per page 
     * @return
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo> findPage(@PathVariable  int page, @PathVariable  int size){
        // Paging query 
        PageInfo<Category> pageInfo = categoryService.findPage(page, size);
        return new Result<PageInfo>(true,StatusCode.OK," The query is successful ",pageInfo);
    }

    /***
     *  Multi criteria search for brand data 
     * @param category
     * @return
     */
    @PostMapping(value = "/search" )
    public Result<List<Category>> findList(@RequestBody(required = false)  Category category){
        List<Category> list = categoryService.findList(category);
        return new Result<List<Category>>(true,StatusCode.OK," The query is successful ",list);
    }

    /***
     *  according to ID Delete brand data 
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable Integer id){
        categoryService.delete(id);
        return new Result(true,StatusCode.OK," Delete successful ");
    }

    /***
     *  modify Category data 
     * @param category
     * @param id
     * @return
     */
    @PutMapping(value="/{id}")
    public Result update(@RequestBody  Category category,@PathVariable Integer id){
        // Set primary key value 
        category.setId(id);
        // Modifying data 
        categoryService.update(category);
        return new Result(true,StatusCode.OK," Modification successful ");
    }

    /***
     *  newly added Category data 
     * @param category
     * @return
     */
    @PostMapping
    public Result add(@RequestBody   Category category){
        categoryService.add(category);
        return new Result(true,StatusCode.OK," Add success ");
    }

    /***
     *  according to ID Inquire about Category data 
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Category> findById(@PathVariable Integer id){
        // according to ID Inquire about 
        Category category = categoryService.findById(id);
        return new Result<Category>(true,StatusCode.OK," The query is successful ",category);
    }

    /***
     *  Inquire about Category All data 
     * @return
     */
    @GetMapping
    public Result<Category> findAll(){
        List<Category> list = categoryService.findAll();
        return new Result<Category>(true, StatusCode.OK," The query is successful ",list) ;
    }

    /**
     *  According to the father ID Inquire about 
     */
    @RequestMapping(value ="/list/{pid}")
    public Result<Category> findByPrantId(@PathVariable(value = "pid")Integer pid){
        // According to the parent node ID Inquire about 
        List<Category> list = categoryService.findByParentId(pid);
        return new Result<Category>(true,StatusCode.OK," The query is successful ",list);
    }
}

 

 

 

原网站

版权声明
本文为[Shuaijie it God]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251145207255.html