- File upload optimization
==========
1.1 url Optimize
explain : If you need to access the server through a network virtual path . It should be implemented in the following configuration .
- Local disk path : D:JT-SOFTimages20200930a.jpg
- Network virtual path : http://image.jt.com20200930a.jpg
1.2 edit pro The configuration file
1.3 Complete the dynamic assignment of attributes
`package com.jt.service;
import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@Service
@PropertySource("classpath:/properties/images.properties") // The container dynamically loads the specified configuration file
public class FileServiceImpl implements FileService{
// Since the value of an attribute may change later , So we should get the attribute data dynamically . utilize pro The configuration file
@Value("${image.rootDirPath}")
private String rootDirPath; // = "D:/JT-SOFT/images";
@Value("${image.urlPath}")
private String urlPath; // = "http://image.jt.com";
//1.2 Prepare a collection of pictures Contains all types of pictures .
private static Set<String> imageTypeSet;
static {
imageTypeSet = new HashSet<>();
imageTypeSet.add(".jpg");
imageTypeSet.add(".png");
imageTypeSet.add(".gif");
}
/**
* Perfect calibration process
* 1. Check whether it is a picture
* 2. Verify whether it is a malicious program
* 3. Prevent too many files , Sub directory storage .
* 4. Prevent duplicate names of files
* 5. File upload .
* @param uploadFile
* @return
*/
@Override
public ImageVO upload(MultipartFile uploadFile) {
//0. Prevent extra space So first do the processing of the space
rootDirPath.trim();
urlPath.trim();
//1. Check image type jpg|png|gif..JPG|PNG....
//1.1 Get the name of the current picture And then intercept the type . abc.jpg
String fileName = uploadFile.getOriginalFilename();
int index = fileName.lastIndexOf(".");
String fileType = fileName.substring(index);
// Convert data to lowercase
fileType = fileType.toLowerCase();
//1.3 Determine whether the picture type is correct .
if(!imageTypeSet.contains(fileType)){
// The image type doesn't match
return ImageVO.fail();
}
//2. Verify whether it is a malicious program According to width / Height to judge
try {
//2.1 utilize an instrument API object Read byte information . Get the image object type
BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
//2.2 Check for width and height
int width = bufferedImage.getWidth();
int height = bufferedImage.getHeight();
if(width==0 || height==0){
return ImageVO.fail();
}
//3. Sub directory storage yyyy/MM/dd Separate
//3.1 Set the time according to the specified format Convert to string .
String dateDir = new SimpleDateFormat("/yyyy/MM/dd/")
.format(new Date());
//3.2 The directory object where the file is stored
String fileDirPath = rootDirPath + dateDir;
File dirFile = new File(fileDirPath);
//3.3 Create a dynamic directory
if(!dirFile.exists()){
dirFile.mkdirs();
}
//4. Prevent duplicate names of files uuid.jpg Dynamic splicing
//4.1 Dynamic generation uuid Realize file name splicing name . suffix
String uuid =
UUID.randomUUID().toString().replace("-", "");
String realFileName = uuid + fileType;
//5 File upload
//5.1 The actual path of the splicing file dir/ File name .
String realFilePath = fileDirPath + realFileName;
//5.2 Encapsulated object Upload
File realFile = new File(realFilePath);
uploadFile.transferTo(realFile);
// File upload success !!! http://image.jt.com20200930a.jpg
String url = urlPath + dateDir + realFileName;
return ImageVO.success(url,width,height);
} catch (IOException e) {
e.printStackTrace();
return ImageVO.fail();
}
}
}`
2 Reverse proxy mechanism
2.1 Why do I need a reverse proxy
demand : When the file upload is complete , What the business returns to the page is the virtual address path
url Address : http://image.jt.com/2020/09/30/a.jpg
Real picture address : file:///D:/JT-SOFT/image/2020/09/30/d534bed912c748b0ac979ee40222490a.jpg
problem : How to let users through url visit Find a picture of the real disk address .
2.2 Reverse proxy mechanism
2.2.1 Introduction to reverse agent
The reverse proxy server is located between the user and the target server , But for users , The reverse proxy server is equivalent to the target server , namely Users can obtain the resources of the target server by directly accessing the reverse proxy server . meanwhile , user You don't need to know the address of the target server , There is no need to make any settings on the client side . A reverse proxy server is usually used as Web Speed up , Use reverse proxy as Web Front end server to reduce network and server load , Improve access efficiency .
Generalization :
1. Located in the user ( client )- Between servers .
2. User access to reverse proxy server , Think it's real server information .
3. Users have no idea who the real server information is .
4. The general mechanism of proxy server to protect the real information , So it's also called Server side agents .
2.3 Forward proxy mechanism
2.3.1 Demand introduction
1. Broadband : Telecom operators account number / password Can only be used by one machine .
2. Router : Created a local area network inside the home The device in LAN can communicate with the outside world through the function of router .
2.3.2 Introduce to agent
Forward agency , It means a location between the client and the original server (origin server) Server between , To get content from the original server , The client sends a request to the agent and specifies the destination ( Original server ), The agent then forwards the request to the original server and returns the obtained content to the client . Client can use forward proxy .
summary :
1. The forward proxy is between the client and the server
2. Before the client initiates the request The address of the target server is determined .
3. The server doesn't know which client is accessing me , Thought it was just router access .
4. Forward proxy protects the customer's information , So it's also called Client agent
2.4 Nginx
2.4.1 Nginx Introduce
Nginx (engine x) Is a high-performance HTTP And reverse proxy web The server , It also provides IMAP/POP3/SMTP service .Nginx It was by igor · Mr. Seshoyev was the second most visited city in Russia Rambler.ru Site ( ru :Рамблер) Developed , The first public version 0.1.0 Published on 2004 year 10 month 4 Japan .
It takes the source code as a class BSD Release in the form of license , Because of its stability 、 Rich feature set 、 Known for sample profiles and low system resource consumption .2011 year 6 month 1 Japan ,nginx 1.0.4 Release .
Nginx It's a lightweight model Web The server / Reverse proxy server and email (IMAP/POP3) proxy server , stay BSD-like Issue under agreement . It is characterized by less memory , Strong concurrency , in fact nginx The concurrency ability of is better in the same type of web server , Used in mainland China nginx Website users have : Baidu 、 JD.COM 、 Sina 、 NetEase 、 tencent 、 Taobao, etc. .
characteristic :
1. Less memory No more than 2M tomcat The server takes up about 600M
2. Strong concurrency 3-5 Ten thousand times / second tomcat The server is about 150-220 Between
2.4.2 Nginx Install and use
matters needing attention :
- Don't put nginx Put it in C Disk and system directory Pay attention to Chinese paths and spaces .
- nginx The server starts up very fast , The window will flash back Just start it once
- nginx Start up will take up 80 port .
- nginx The command must run in nginx.exe Execute... In the directory .
2.4.2 Nginx command
1). Start command start nginx
2). Restart command nginx -s reload
3). Stop the order nginx -s stop
2.4.3 Nginx Server startup item description
2.4.4 About nginx Reverse proxy description
`http {
# A reverse proxy is a server
server {
# monitor 80 port
listen 80;
# Monitored domain name Domain name cannot be repeated .
server_name localhost;
# The reverse proxy action performed / Block all paths
location / {
# root keyword The agent is a directory
root html;
# Default jump page
index index.html index.htm;
}
}
}`
2.5 Nginx Realize image echo
2.5.1 NGINX To configure
`# Image server agent image.jt.com:80
server {
listen 80;
server_name image.jt.com;
location / {
# Turn to the catalog
root D:/JT-SOFT/images;
}
}`
2.5.2 modify hosts file
1.HOSTS Description of the document :
2.HOSTS The location of the file
3). Run as super administrator
`# Jingtao configuration
# On the left IP Address Write the domain name on the right Use a space between them
127.0.0.1 image.jt.com
127.0.0.1 manage.jt.com
# Realization nginx Of
#192.168.126.129 image.jt.com
#192.168.126.129 manage.jt.com
127.0.0.1 www.jt.com
#Bug Sometimes the letters may be lost when using the software .
127.0.0.1 sso.jt.com`
3.nginx Realization tomcat Cluster deployment
3.1 Project deployment
3.2 Server reverse proxy
`# Configure Jingtao background management server
# manage.jt.com localhost:8091 The server
server {
listen 80;
server_name manage.jt.com;
location / {
# Mapping server
proxy_pass http://localhost:8091;
}
}`
modify nignx After the server , restart nginx
3.3 Get the current server port number dynamically
`@RestController
public class PortController {
// from spring Dynamic access to the server port number
@Value("${server.port}")
private Integer port;
@RequestMapping("/getPort")
public String getPort(){
return " Current server access port number :"+port;
}
}`
3.4 Project package
And then from the project target Get dynamically from the directory jar Package file Prepare for cluster deployment .
3.4 Project release order
matters needing attention : The current command is executed Will occupy dos Command window Print console information . When dos The command window closes The server stops .
sign out dos Command window : ctrl + c
`java: java -jar 8081.war`
* 1
3.4 nginx Load balancing implementation
3.4.1 Polling mechanism
explain : In the order of the configuration files Access the server in turn .
`# Configure Jingtao background management server
# manage.jt.com localhost:8091 The server
server {
listen 80;
server_name manage.jt.com;
location / {
# Mapping server
#proxy_pass http://localhost:8091;
proxy_pass http://jtWindows;
}
}
# To configure tomcat Server cluster 1. Polling strategy
upstream jtWindows {
#server Represents the server address
server 127.0.0.1:8081;
server 127.0.0.1:8082;
}`
3.4.2 Weight mechanism
explain : According to the weight setting , Let the server with better performance handle more requests .
`# To configure tomcat Server cluster 1. Polling strategy 2. Weight strategy
upstream jtWindows {
#server Represents the server address
server 127.0.0.1:8081 weight=8;
server 127.0.0.1:8082 weight=2;
}`
3.4.3 IPHASH Strategy ( understand )
Because some data is bound to the server , Then you have to ask the user to access the specified server , Use IPHASH Strategy
`# To configure tomcat Server cluster 1. Polling strategy 2. Weight strategy 3.iphash Strategy
upstream jtWindows {
#server Represents the server address
ip_hash;
server 127.0.0.1:8081 weight=8;
server 127.0.0.1:8082 weight=2;
}`
Homework
1. install VMware Virtual machine program
2. Check the network card settings
If there is no network card Then change it to another one vmwar Version installed …
- start-up Linux System
Problem description :
Get into BIOS In the system Turn on the virtualization settings . Motherboard system Turn it on F1/F2…