Springboot uses jar package files to upload echo and deploy the cloud


In recent days, I've tried to deploy the cloud by using the jar package of springboot to summarize the experience and problems encountered

1, The springboot project deploys cloud Linux

1. Pack

1. Set an unused port on the cloud, which will be occupied by spring boot running in the form of jar package

2. Change pom.xml packaging method to jar

3. Package with maven tool, clean it first, and then package it into jar package

After packaging, a. jar file is generated

2. Upload ECS

3. linux commands related to deploying jar packages

Start:

#Run the jar package (terminate after closing the terminal)
java -jar xxx.jar	
#Run in nohup mode, and still run in the background after closing the terminal. The jar package operation log is output in webLog.txt
nohup java -jar xxx.jar > webLog.txt & 		

How to close nohup java?

#Find all java processes and see which process our project is
ps aux | grep java
#Find the pid of the project and close it with kill
kill -9  pid

2, Path problem of file upload in jar package mode

1. Problem introduction

In the idea development tool, we do not run in the jar package mode. When uploading files, we often choose to upload them to a directory under target/classes/static

**For example: * * take my image upload function for example. My idea is to transfer the uploaded images to the static directory, because springboot automatically configures the static directory to directly read the image resources with / upload/xxx.jpg. At the end of the function, I directly return the access path / upload/filName to the front end, and the images can be read in the idea.

@RequestMapping("/uploadImage")
    @ResponseBody
    public JSONObject uploadImg (MultipartFile file) throws Exception{

        //file extension
        String trueFileName = file.getOriginalFilename();
        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));

        //File name random + suffix
        String fileName = "teachers-"+ UUID.randomUUID().toString().replaceAll("-", "") +suffix;

        File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
        //The project path is absolutely mywebproject\target\classes
        String absolutePath = projectPath.getAbsolutePath();
        //Put it in the / static/upload / directory
        String path = absolutePath+"/static/upload/";
        System.out.println(path);

        //Create folder without
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //preservation
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //Return to front-end file location
        JSONObject res = new JSONObject();
        res.put("url", "/upload/"+fileName);
        res.put("success", 1);
        res.put("message", "upload success!");

        return res;

    }

However, when I upload it to the cloud and run it as a jar package, the pictures I upload cannot be uploaded to the specified location, but / mysprinboot / file: / mysprinboot / mywebproject-1.0-snapshot.jar is generated at the same level of the jar package/ BOOT-INF/classes!/ A directory like static / upload

Reason: after decompressing the jar package, we found that the static directory is in the jar package, but the operating system does not allow us to modify the contents of the jar package. This causes the operating system to generate a new directory to store the uploaded files

2. Problem solving:

Since it is not generated in the project path, we can use ① file stream to read or ② configure virtual static resource mapping

Here I only show method 2: ② configure virtual static resource mapping

From the directory generated above, we can know that on my ECs, the absolute path of image upload is / mysprinboot / file: / mysprinboot / mywebproject-1.0-snapshot.jar/ BOOT-INF/classes!/ static/upload

In spring boot, we can implement WebMvcConfigurer to add static resource processing mapping

@Configuration
public class MvcConfig implements WebMvcConfigurer {    
  	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //addResourceLocations is our absolute path for file upload. Note that file:
    //addResourceHandler is our mapping address, that is, the pictures uploaded to ResourceLocations can be retrieved with / upload/xxx.jpg
	registry.addResourceHandler("/upload/**").addResourceLocations("file:/mySpringBoot/file:/mySpringBoot/mywebproject-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/static/upload/");
    }
}

**Note: * * file should be added to the path in addResourceLocations():

At this time, when running the project again, you can get it through the ECS host address: port number / upload/xxx.jpg. The problem is solved

For the convenience of future modification, we write this path in the yaml configuration file

#linux upload file address
bandit:
  upload: file:/mySpringBoot/file:/mySpringBoot/mywebproject-1.0-SNAPSHOT.jar!/BOOT-INF/classes!/static/upload/

Then get this Value in the configuration class @ Value, as shown in the following configuration

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    
    @Value("${bandit.upload}")
    private String uploadPath;
    
  	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	registry.addResourceHandler("/upload/**").addResourceLocations(uploadPath);
    }
}

Keywords: Java Spring Spring Boot jar

Added by jmaker on Wed, 08 Dec 2021 02:12:17 +0200