SpringBoot集成FDFS

一.配置文件引入

## 文件系统配置信息 
fastdfs.download=10.25.0.241:8888 
fastdfs.tracker_servers=10.25.0.241:22122 
fastdfs.charset=UTF-8 
fastdfs.connect_timeout_in_seconds=10 
fastdfs.http_anti_steal_token=no 
fastdfs.http_tracker_http_port=8888 
fastdfs.network_timeout_in_seconds=30

二. Config文件

@Configuration
public class FastDfsConfig {
    private static final Logger log = LoggerFactory.getLogger(FastDfsConfig.class);
​
    @Value("${fastdfs.connect_timeout_in_seconds}:10")
    private String connectTimeoutInSeconds;
    @Value("${fastdfs.network_timeout_in_seconds}:30")
    private String networkTimeoutInSeconds;
    @Value("${fastdfs.charset:UTF-8}")
    private String charset;
    @Value("${fastdfs.http_anti_steal_token}:no")
    private String httpAntiStealToken;
    @Value("${fastdfs.http_tracker_http_port}:8888")
    private String httpTrackerHttpPort;
    @Value("${fastdfs.tracker_servers}")
    private String trackerServers;
​
    public Properties initFastDfsProperties() {
        Properties properties = new Properties();
        properties.setProperty("fastdfs.connect_timeout_in_seconds", connectTimeoutInSeconds);
        properties.setProperty("fastdfs.network_timeout_in_seconds", networkTimeoutInSeconds);
        properties.setProperty("fastdfs.charset", charset);
        properties.setProperty("fastdfs.http_anti_steal_token", httpAntiStealToken);
        properties.setProperty("fastdfs.http_tracker_http_port", httpTrackerHttpPort);
        properties.setProperty("fastdfs.tracker_servers", trackerServers);
        return properties;
    }
​
    @Bean
    public StorageClient1 initStorageClient() {
        try {
            Properties properties = initFastDfsProperties();
            ClientGlobal.initByProperties(properties);
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
            return new StorageClient1(trackerServer, storeStorage);
        } catch (IOException | MyException e) {
            e.printStackTrace();
        }
        throw new RunTimeException("FDFS初始化错误");
    }

三. 上传

 @Resource
    StorageClient1 storageClient;
    
    public String uploadFile(MultipartFile file) {
        if (Objects.isNull(file)) return null;
        String name = file.getOriginalFilename();
        if (Objects.isNull(name)) return null;
        String[] names = name.split("\\.");
        try {
            byte[] bytes = file.getBytes();
            return storageClient.upload_file1(bytes, names[names.length - 1], null);
        } catch (IOException | MyException exception) {
            exception.printStackTrace();
        }
        throw new ErrorCenterException(ExceptionEnum.FAST_DFS_UPDATE_ERROR.getEasyCode());
    }

 

posted @ 2020-08-10 08:51  七柏  阅读(729)  评论(0编辑  收藏  举报