fastdfs是轻量级小文件存储不错的选择。网上有大量的资料介绍,这里就不多说了。github地址是:https://github.com/happyfish100/fastdfs。
./make.sh
./make.sh install
./make.sh
./make.sh install
拷贝conf目录中的http.conf和mime.types到/etc/fdfs目录。这里一定要注意否则报错!!
2.配置文件和启动:
[group1]
group_name=test
storage_server_port=23000
store_path_count=1
store_path0=/data/fastdfs/storagetest/storefile
[group2]
group_name=prod
storage_server_port=24000
store_path_count=1
store_path0=/data/fastdfs/storageprod/storefile
./configure --prefix=/opt/nginx --with-http_stub_status_module --with-http_ssl_module --with-pcre=/opt/pcre-8.42 --with-openssl=/opt/openssl-1.0.2q --with-zlib=/opt/zlib-1.2.11 --with-http_realip_module --add-module=/opt/fastdfs-nginx-module-master/src
make
make install
fdfs:
fastdfs.connect_timeout_in_seconds: 5
fastdfs.network_timeout_in_seconds: 30
fastdfs.charset: UTF-8
fastdfs.http_anti_steal_token: false
fastdfs.http_tracker_http_port: 22122
fastdfs.http_secret_key: FastDFS1234567890
fastdfs.tracker_servers: 127.0.0.1:22122
application-test.yml 放测试环境
fdfs:
groupName: test
application-prod.yml 放生产环境
fdfs:
groupName: prod
写一个properties来接收配置
@ConfigurationProperties("")
public class FdfsProperties {
private final Map<String, String> fdfs = new HashMap<>();
public Map<String, String> getFdfs() {
return fdfs;
}
}
文件上传的类
@Component
public class FileManager {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private FdfsProperties fdfsProperties;
@PostConstruct
public void init() throws IOException, MyException {
Properties properties=new Properties();
properties.putAll(fdfsProperties.getFdfs());
//写入fdfs配置
ClientGlobal.initByProperties(properties);
}
public String upload(FileItem file) {
TrackerServer trackerServer=null;
try {
TrackerClient trackerClient = new TrackerClient();
trackerServer= trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient1 storageClient = new StorageClient1(trackerServer,storageServer);
NameValuePair[] metas=new NameValuePair[]{new NameValuePair("fileName",file.getFileName())};
String result = storageClient.upload_file1(fdfsProperties.getFdfs().get("groupName"),file.getContent(), file.getFileName().split("\\.")[1],metas);
return result;
} catch (Exception e) {
log.error(Throwables.getStackTraceAsString(e));
throw new BusinessException("上传错误!");
} finally {
if(trackerServer!=null){
try {
trackerServer.close();
} catch (IOException e) {
throw new BusinessException("上传错误!");
}
}
}
}
}
FileItem.java
public class FileItem implements Serializable{
private String fileName;
private byte[] content;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public byte[] getContent() {
return content;
}
public void setContent(byte[] content) {
this.content = content;
}
}