FastDFS与springboot整合例子
余庆先生提供了一个Java客户端,但是作为一个C程序员,写的java代码可想而知。而且已经很久不维护了。
这里推荐一个开源的FastDFS客户端,支持最新的SpringBoot2.0。
配置使用极为简单,支持连接池,支持自动生成缩略图,狂拽酷炫吊炸天啊,有木有。
引入依赖
在父工程中,我们已经管理了依赖,版本为:
<fastDFS.client.version>1.25.2-RELEASE</fastDFS.client.version>
因此,这里我们直接引入坐标即可:
<dependency> <groupId>com.github.tobato</groupId> <artifactId>fastdfs-client</artifactId> </dependency>
引入配置类
纯java配置:
@Configuration @Import(FdfsClientConfig.class) // 解决jmx重复注册bean的问题 @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class FastClientImporter { }
编写FastDFS属性
fdfs: so-timeout: 1501 connect-timeout: 601 thumb-image: # 缩略图 width: 60 height: 60 tracker-list: # tracker地址 - 192.168.56.101:22122
测试
@RunWith(SpringRunner.class) @SpringBootTest(classes = LyUploadService.class) public class FdfsTest { @Autowired private FastFileStorageClient storageClient; @Autowired private ThumbImageConfig thumbImageConfig; @Test public void testUpload() throws FileNotFoundException { File file = new File("D:\\test\\baby.png"); // 上传并且生成缩略图 StorePath storePath = this.storageClient.uploadFile( new FileInputStream(file), file.length(), "png", null); // 带分组的路径 System.out.println(storePath.getFullPath()); // 不带分组的路径 System.out.println(storePath.getPath()); } @Test public void testUploadAndCreateThumb() throws FileNotFoundException { File file = new File("D:\\test\\baby.png"); // 上传并且生成缩略图 StorePath storePath = this.storageClient.uploadImageAndCrtThumbImage( new FileInputStream(file), file.length(), "png", null); // 带分组的路径 System.out.println(storePath.getFullPath()); // 不带分组的路径 System.out.println(storePath.getPath()); // 获取缩略图路径 String path = thumbImageConfig.getThumbImagePath(storePath.getPath()); System.out.println(path); } }
结果:
group1/M00/00/00/wKg4ZVro5eCAZEMVABfYcN8vzII630.png M00/00/00/wKg4ZVro5eCAZEMVABfYcN8vzII630.png M00/00/00/wKg4ZVro5eCAZEMVABfYcN8vzII630_60x60.png