使用分布式文件系统 DFS
微服务应用使用分布式方式进行部署,并且有可能随时随地部署多个副本,所以必须有一个独立的文件系统来管理用户上传和使用的资源文件,包括图片和视频等。
在模块goods-web 的设计中,我们是使用FastDFS这个轻量级的分布式文件系统来设计的。如果使用云服务商提供的对象存储服务来设计,如OSS服务等,则可以参照服务提供商的使用说明,并结合本实例进行设计。
下面针对库存管理中,商品创建和编辑时使用的图片,实现在FastDFS上进行存储和管理的设计。
有关FastDFS的安装、集群构建和相关配置等,将在运维部署部分的相关章节中进行介绍。
分布式文件系统客户端开发
FastDFS 提供了Java语言使用的客户端开发包,但在Spring Boot中使用时还需要进行二次开发。为了简化开发过程,我们使用tobato在GitHub上开源的一个专为Spring Boot开发者提供的封装。
首先,在goods-web模块中,增加如下依赖引用:
<dependency>
<groupId>com.github.tobato</groupId><artifactId>fastdfs-client</artifactId><version>1.26.4-RELEASE</version>
</dependency>
然后,在模块的配置文件application.yml 中增加如下配置:
fdfs:
soTimeout: 1501
connectTimeout:601thumbImage:
width: 150height: 150trackerList:
- 192.168.1.214:22122-192.168.1.215:22122spring.jmx.enabled: false
file.path.head:http://192.168.1.214:8080/
这个配置假设 FastDFS 的TrackerServer安装了两台服务器,它们的P地址分别为“192.168.1.214”和“192.168.1.215”,并且可以通过链接“http:/192.168.1.214:8080/”使用文件。
接着,在工程的启动文件中增加注解@Import和@EnableMBeanExport,即导入fastdfs-client的相关配置,代码如下所示:
@SpringBootApplication@EnableDiscoveryClient
@EnableFeignClients (basePackages = "com.demo")@componentScan(basePackages = "com.demo")
R Import(FdfsClientConfig.class)
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)public class GoodswebApplication {
public static void main(String[]args) {
SpringApplication.run (GoodsWebApplication.class, args);
}
}
为了确认上面的引用和配置都已经准备就绪,可以启动应用验证一下。如果启动应用正常,则说明上面的配置是正确的。
现在,我们就可以创建一个“FastefsClient”实现文件的上传功能了,代码如下所示:
@service
public class FastefsClient {
@Autowired
protected FastFileStorageClient storageClient;
public String uploFile (MultipartFile file){
String fileType=
FilenameUtils.getExtension(file.get0riginalFilename ()).toLowerCase();
StorePath path =null;
try {
path = storageclient.uploadFile(file.getInputstream(),
file.getsize(, fileType, nul1);
Jcatch (IOException e){
e.printstackTrace();
}
if(path !=null) {
return path.getFu1lPath(;}else {
return null;
}
public string uploile(Inputstream inputstream,Long size, String type)(
StorePath path = null;
try {
path = storageclient.uploadFile(inputStream, size, type, null);}catch(Exception e){
e.printStackTrace();
}
if(path!=null) {
return path. getFullPath();}else i
return null;
public boolean deleteFile(string fullPath)
try {
storageClient.deleteFile(fullPath);return true;
}catch(Exception e){
e-printstackTrace(;
}
return false;
}
}
这里,设计了一个多态的uploFile方法,可以使用不同的参数通过调用FastFileStorageClient实现文件上传,同时设计了一个deleteFile方法,实现文件的删除操作。
商品图片上传设计
商品图片上传步骤如下。
首先,设计一个控制器PicUtilController;然后,在这个控制器中实现文件上传的功能,代码如下所示:
@Controller
@RequestMapping("/pic")
public class PicUtilController {
@value("${file.path.head:http://192.168.1.214:84/}")private String pathHead;
GAutowired
private FastefsClient fastefsClient;
//可缩放图片上传
CRequestM