通過Zuul閘道器實現檔案上傳
阿新 • • 發佈:2018-12-11
- 上傳檔案含有中文名,需要為上傳路徑新增 /zuul 字首(當前版本貌似已經修復,不需要新增 /zuul 字首也可以)
- 對於小檔案(1M以內)上傳無需任何處理,對於大檔案(10M以上)上傳,需要為上傳路徑新增 /zuul 字首,也可以使用 zuul.servlet-path 自定義字首
- 假設 zuul.routes.file-upload = /file-upload/**,如果 http://{HOST}:{PORT}/uoload 是微服務 file-upload 上傳路徑,則可以使用 Zuul 的 /zuul/file-upload/upload 路徑上傳大檔案
- 如果 Zuul 使用 Ribbon 做負載均衡,那麼對於超大檔案(例如500M)需要提升超時時間
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=60000
ribbon.ConnectTimeout=3000
ribbon.ReadTimeout= 60000
新增 /zuul 字首是指需要使用ZuulServlet來實現檔案上傳。
示例
第一步,建立一個Maven專案用來測試上傳,命名file-upload,並引入以下依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
第二步,建立應用主類Application。
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
第三步,建立UploadController。
@RestController public class UploadController { @PostMapping(name = "/file-upload") public String handleFileUpLoad(@RequestParam(value = "file") MultipartFile file) throws IOException { System.out.println(file.getSize()); byte[] bytes = file.getBytes(); File fileToSave = new File(file.getOriginalFilename()); FileCopyUtils.copy(bytes, fileToSave); String path = fileToSave.getAbsolutePath(); System.out.println(path); return path; } }
第四步,建立配置檔案application.yml。
spring:
application:
name: file-upload
servlet:
multipart:
max-file-size: 2000Mb
max-request-size: 2500Mb
server:
port: 5555
eureka:
client:
service-url:
defaultZone: http://localhost:1111/eureka/ #指定服務註冊中心位置
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ip-address}:${server.port}
第五步,在API閘道器服務新增路由規則。
zuul:
routes:
upload:
path: /upload/**
serviceId: file-upload
測試
啟動服務註冊中心,即eureka-server-vFinchley.Rc2工程
啟動服務提供者file-upload,即file-upload工程
啟動Zuu的APIl閘道器服務api-gateway,即api-gateway-vFinchley.RC2工程
由於是POST請求,使用postman來測試。
先不通過API閘道器上傳檔案
上傳小檔案,檔案大小44kb,成功
通過API閘道器服務上傳檔案
上傳小檔案,成功
上傳大檔案,失敗
新增 /zuul 字首重寫上傳,成功
如果你的檔案太大,比如1G以上,可能會報以下錯誤
There was an unexpected error (type=Internal Server Error, status=500).
TIMEOUT
修改Zuul的超時配置重新上傳就好了。
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=60000
ribbon.ConnectTimeout=3000
ribbon.ReadTimeout= 60000