SpringBoot适配fastdfs
添加关于fastdfs的pom依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.79/version>
</dependency>
配置文件中需要配置相关参数
#-------FastDFS配置,后端上传文件时需要读取的------
fdfsread_confFileName=application.properties # 这个后面会专门提到
connect_timeout=100
network_timeout=300
charset=ISO8859-1
tracker_server=10.16.2.57:22122
fdfsread_server=10.16.2.57
http.tracker_http_port=80
tracker_port=22122
提供测试类
@RestController
@RequestMapping("/file")
@Component
public class FileUploadCtrl{
@Override
@PostMapping("/upload")
public ResponseEntity<String> uploadContractFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
try {
Map<String, String> searchParams = getSearchParamsFromRequest(request);
if (!searchParams.containsKey("type") || StringUtils.isBlank((String) searchParams.get("type"))) {
return HeaderUtil.createOkEntity("type参数不得为空", "0", null);
}
String type = searchParams.get("type");
byte[] byteFile = file.getBytes();
String attachment = fileManager.uploadFile("\\." + type, byteFile);
return HeaderUtil.createOkEntity(null, "1", "/" + attachment);
} catch (Exception e) {
e.printStackTrace();
return HeaderUtil.createOkEntity(e.getMessage(), "2", null);
}
}
/**
* @param @param request
* @param @return 设定文件
* @return Map<String, String> 返回类型
* @throws
* @Title: getSearchParamsFromRequest
* @Description: 从request中拿到参数MAP
*/
private Map<String, String> getSearchParamsFromRequest(HttpServletRequest request) {
Map<String, String> searchParams = new HashMap<>();
Enumeration<String> enumeration = request.getParameterNames();
while (enumeration.hasMoreElements()) {
String args = enumeration.nextElement();
searchParams.put(args, request.getParameter(args));
}
return searchParams;
}
}
封装上传公共类
@Component
public class FileManager {
@Value("${fdfsread_confFileName}")
private String confFileName;
//下面讲到这个是什么作用
@Autowired
private FastdfsProperties fastdfsProperties;
public static Logger logger = LoggerFactory.getLogger(FileManager.class);
public FileManager() {
}
public String uploadFile(String fileName, byte[] fileContent) {
String saveName = UUID.randomUUID().toString() + "_" + fileName;
try {
NameValuePair[] metaData = new NameValuePair[]{};
FastdfsClient client = FastdfsClient.getInstance(fileName,fastdfsProperties);
saveName = client.upload(metaData, fileContent, fileName);
} catch (Exception e) {
saveName = null;
logger.error("fastdfs上传出错", e);
throw new BusinessException("fastdfs上传出错:" + e.getMessage());
}
return saveName;
}
public byte[] downLoadFile(String fileName) {
byte[] contents = null;
try {
contents = FastdfsClient.getInstance(confFileName,fastdfsProperties).download(fileName);
if (contents == null) {
logger.error("没有找到文件内容!");
throw new BusinessException("没有找到文件内容!");
}
} catch (Exception e) {
logger.error("fastdfs下载失败!");
throw new BusinessException("fastdfs下载失败:" + e.getMessage());
}
return contents;
}
public boolean deleteFile(String fileName) {
boolean flag = false;
FastdfsClient client = FastdfsClient.getInstance(confFileName,fastdfsProperties);
try {
flag = client.delete(fileName);
} catch (Exception e) {
logger.error("fastdfs删除失败!");
throw new BusinessException("fastdfs删除失败:" + e.getMessage());
}
return flag;
}
}
FastdfsClient
public class FastdfsClient {
public static Logger logger = LoggerFactory.getLogger(FastdfsClient.class);
private static volatile FastdfsClient fdfsClient;
private TrackerClient tracker;
private FastdfsClient() {
private FastdfsClient(String confFileName) {
try {
String confRealUrl = Thread.currentThread().getContextClassLoader().getResource(confFileName).getPath().toString();
ClientGlobal.init(confRealUrl);
this.tracker = new TrackerClient();
} catch (FileNotFoundException var4) {
logger.error("未找到fdfs对应的配置文件!", var4);
} catch (Exception var5) {
logger.error("初始化FastdfsClient报错!", var5);
}
}
}
private FastdfsClient(String confFileName,FastdfsProperties properties) {
try {
initClientGlobal(confFileName,properties);
this.tracker = new TrackerClient();
} catch (FileNotFoundException var4) {
logger.error("未找到fdfs对应的配置文件!", var4);
} catch (Exception var5) {
logger.error("初始化FastdfsClient报错!", var5);
}
}
public static FastdfsClient getInstance(String confFileName) {
if (fdfsClient == null || fdfsClient.tracker == null) {
Class var0 = FastdfsClient.class;
synchronized(FastdfsClient.class) {
if (fdfsClient == null || fdfsClient.tracker == null) {
fdfsClient = new FastdfsClient(confFileName);
}
}
}
return fdfsClient;
}
public static FastdfsClient getInstance(String confFileName,FastdfsProperties properties) {
if (fdfsClient == null || fdfsClient.tracker == null) {
Class var0 = FastdfsClient.class;
synchronized(FastdfsClient.class) {
if (fdfsClient == null || fdfsClient.tracker == null) {
fdfsClient = new FastdfsClient(confFileName,properties);
}
}
}
return fdfsClient;
}
/**
* 初始化ClientGlobal
* @param confFileName
* @param properties
* @throws MyException
*/
private void initClientGlobal(String confFileName,FastdfsProperties properties) throws FileNotFoundException, IOException, MyException {
ClientGlobal.setG_connect_timeout(properties.getConnectTimeout()*1000);
ClientGlobal.setG_network_timeout(properties.getNetworkTimeout()*1000);
ClientGlobal.setG_charset(properties.getCharset());
String[] szTrackerServers = getTrackerServerValues(properties.getTrackerServer());
if(szTrackerServers == null){
throw new MyException("item \"tracker_server\" in " + confFileName + " not found");
}else{
InetSocketAddress[] tracker_servers = new InetSocketAddress[szTrackerServers.length];
for(int i = 0; i < szTrackerServers.length; ++i) {
String[] parts = szTrackerServers[i].split("\\:", 2);
if (parts.length != 2) {
throw new MyException("the value of item \"tracker_server\" is invalid, the correct format is host:port");
}
tracker_servers[i] = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim()));
}
ClientGlobal.setG_tracker_group(new TrackerGroup(tracker_servers));
ClientGlobal.setG_tracker_http_port(properties.getTrackerHttpPort());
ClientGlobal.setG_anti_steal_token(properties.getAntiStealToken());
if (ClientGlobal.getG_anti_steal_token()) {
ClientGlobal.setG_secret_key(properties.getSecretKey()); }
}
}
/**
* @param obj
* @return
*/
private static String[] getTrackerServerValues(Object obj) {
if (obj == null) {
return null;
} else {
String[] values;
if (obj instanceof String) {
values = new String[]{(String)obj};
return values;
} else {
Object[] objs = ((ArrayList)obj).toArray();
values = new String[objs.length];
System.arraycopy(objs, 0, values, 0, objs.length);
return values;
}
}
}
public String upload(NameValuePair[] metaData, byte[] fileContent, String fileName) throws Exception {
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
return this.upload(fileContent, (NameValuePair[])metaData, prefix);
}
public String upload(byte[] fileContent, String fileName) throws Exception {
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
return this.upload(fileContent, (NameValuePair[])null, prefix);
}
public String upload(String localFilePath) throws Exception {
return this.upload((String)localFilePath, (NameValuePair[])null);
}
public String upload(byte[] fileContent) throws Exception {
return this.upload(fileContent, (NameValuePair[])null);
}
public String upload(String localFilePath, NameValuePair[] metaData) throws Exception {
if (null == localFilePath) {
throw new Exception("FDFSClient invalid arguement");
} else {
TrackerServer trackerServer = null;
StorageClient1 storageClient = null;
String master_file_id = null;
try {
trackerServer = this.tracker.getConnection();
StorageServer storageServer = null;
storageClient = new StorageClient1(trackerServer, (StorageServer)storageServer);
master_file_id = storageClient.upload_file1(localFilePath, (String)null, metaData);
} finally {
if (trackerServer != null) {
trackerServer.close();
}
}
return master_file_id;
}
}
public String upload(byte[] fileContent, NameValuePair[] metaData) throws Exception {
if (null == fileContent) {
throw new Exception("FDFSClient invalid arguement");
} else {
TrackerServer trackerServer = null;
StorageClient1 storageClient = null;
String master_file_id = null;
try {
trackerServer = this.tracker.getConnection();
StorageServer storageServer = null;
storageClient = new StorageClient1(trackerServer, (StorageServer)storageServer);
master_file_id = storageClient.upload_file1(fileContent, "jpg", metaData);
} finally {
if (trackerServer != null) {
trackerServer.close();
}
}
return master_file_id;
}
}
public String upload(byte[] fileContent, NameValuePair[] metaData, String prefix) throws Exception {
if (null != fileContent && null != prefix) {
TrackerServer trackerServer = null;
StorageClient1 storageClient = null;
String master_file_id = null;
try {
trackerServer = this.tracker.getConnection();
StorageServer storageServer = null;
storageClient = new StorageClient1(trackerServer, (StorageServer)storageServer);
master_file_id = storageClient.upload_file1(fileContent, prefix, metaData);
} finally {
if (trackerServer != null) {
trackerServer.close();
}
}
return master_file_id;
} else {
throw new Exception("FDFSClient invalid arguement");
}
}
public NameValuePair[] getMetaData(String fileId) throws Exception {
if (null == fileId) {
throw new Exception("FDFSClient invalid arguement");
} else {
TrackerServer trackerServer = null;
StorageClient1 storageClient = null;
NameValuePair[] nvPair = null;
try {
trackerServer = this.tracker.getConnection();
StorageServer storageServer = null;
storageClient = new StorageClient1(trackerServer, (StorageServer)storageServer);
nvPair = storageClient.get_metadata1(fileId);
} finally {
if (trackerServer != null) {
trackerServer.close();
}
}
return nvPair;
}
}
public boolean delete(String filePath) throws Exception {
if (null == filePath) {
throw new Exception("FDFSClient invalid arguement");
} else {
TrackerServer trackerServer = null;
StorageClient1 storageClient = null;
boolean success = false;
try {
trackerServer = this.tracker.getConnection();
StorageServer storageServer = null;
storageClient = new StorageClient1(trackerServer, (StorageServer)storageServer);
if (storageClient.delete_file1(filePath) == 0) {
success = true;
}
} finally {
if (trackerServer != null) {
trackerServer.close();
}
}
return success;
}
}
public InputStream download(String fileId, String localFilePath) throws Exception {
if (null != fileId && null != localFilePath) {
return new ByteArrayInputStream(this.download(fileId));
} else {
throw new Exception("FDFSClient invalid arguement");
}
}
public byte[] download(String fileId) throws Exception {
if (null == fileId) {
throw new Exception("FDFSClient invalid arguement");
} else {
TrackerServer trackerServer = null;
StorageClient1 storageClient = null;
Object var4 = null;
byte[] fileContent;
try {
trackerServer = this.tracker.getConnection();
StorageServer storageServer = null;
storageClient = new StorageClient1(trackerServer, (StorageServer)storageServer);
fileContent = storageClient.download_file1(fileId);
} finally {
if (trackerServer != null) {
trackerServer.close();
}
}
return fileContent;
}
}
}
搞定之后,可以进行测试:
String confRealUrl = Thread.currentThread().getContextClassLoader().getResource(confFileName).getPath().toString();
这个的作用是:获取配置文件的路径进行加载,然后获取对应配置文件中的关于FastDfs的配置信息,实例化ClientGlobal对象。
/D:/CRM/workSpace/fuseWorkSpace/occ-kb-web/target/classes/application.properties
但是我们将服务打成jar包后,便报错,对应路径为
/data/fmcg-occ/tomcat-kb/webapps/ROOT/WEB-INF/lib/occ-common-web-2022.1.0-SNAPSHOT.jar! /application-common-test52.properties
那么需要我们了解一下ClientGlobal,看源码核心内容,
即:获取配置文件的路径进行加载,然后获取对应配置文件中的关于FastDfs的配置信息,实例化ClientGlobal对象
//此时获取不到对应的文件
IniFileReader iniReader = new IniFileReader(conf_filename);
g_connect_timeout = iniReader.getIntValue("connect_timeout", 5);
public class ClientGlobal {
public static int g_connect_timeout;
public static int g_network_timeout;
public static String g_charset;
public static int g_tracker_http_port;
public static boolean g_anti_steal_token;
public static String g_secret_key;
public static TrackerGroup g_tracker_group;
public static final int DEFAULT_CONNECT_TIMEOUT = 5;
public static final int DEFAULT_NETWORK_TIMEOUT = 30;
private ClientGlobal() {
}
public static void init(String conf_filename) throws FileNotFoundException, IOException, MyException {
IniFileReader iniReader = new IniFileReader(conf_filename);
g_connect_timeout = iniReader.getIntValue("connect_timeout", 5);
if (g_connect_timeout < 0) {
g_connect_timeout = 5;
}
g_connect_timeout *= 1000;
g_network_timeout = iniReader.getIntValue("network_timeout", 30);
if (g_network_timeout < 0) {
g_network_timeout = 30;
}
g_network_timeout *= 1000;
g_charset = iniReader.getStrValue("charset");
if (g_charset == null || g_charset.length() == 0) {
g_charset = "ISO8859-1";
}
String[] szTrackerServers = iniReader.getValues("tracker_server");
if (szTrackerServers == null) {
throw new MyException("item \"tracker_server\" in " + conf_filename + " not found");
} else {
InetSocketAddress[] tracker_servers = new InetSocketAddress[szTrackerServers.length];
for(int i = 0; i < szTrackerServers.length; ++i) {
String[] parts = szTrackerServers[i].split("\\:", 2);
if (parts.length != 2) {
throw new MyException("the value of item \"tracker_server\" is invalid, the correct format is host:port");
}
tracker_servers[i] = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim()));
}
g_tracker_group = new TrackerGroup(tracker_servers);
g_tracker_http_port = iniReader.getIntValue("http.tracker_http_port", 80);
g_anti_steal_token = iniReader.getBoolValue("http.anti_steal_token", false);
if (g_anti_steal_token) {
g_secret_key = iniReader.getStrValue("http.secret_key");
}
}
}
}
通过分析源码,其实就是获取配置文件信息,那我们该怎么做
可以在启动服务时获取配置文件内容,后面建ClientGlobal时进行重写,但是我们发现ClientGlobal重写不了,那么我们可以将整个类进行重写。
public class ClientGlobal {
public static int g_connect_timeout;
public static int g_network_timeout;
public static String g_charset;
public static int g_tracker_http_port;
public static boolean g_anti_steal_token;
public static String g_secret_key;
public static TrackerGroup g_tracker_group;
public static final int DEFAULT_CONNECT_TIMEOUT = 5;
public static final int DEFAULT_NETWORK_TIMEOUT = 30;
private ClientGlobal() {
}
public static void init(String conf_filename) throws FileNotFoundException, IOException, MyException {
IniFileReader iniReader = new IniFileReader(conf_filename);
g_connect_timeout = iniReader.getIntValue("connect_timeout", 5);
if (g_connect_timeout < 0) {
g_connect_timeout = 5;
}
g_connect_timeout *= 1000;
g_network_timeout = iniReader.getIntValue("network_timeout", 30);
if (g_network_timeout < 0) {
g_network_timeout = 30;
}
g_network_timeout *= 1000;
g_charset = iniReader.getStrValue("charset");
if (g_charset == null || g_charset.length() == 0) {
g_charset = "ISO8859-1";
}
String[] szTrackerServers = iniReader.getValues("tracker_server");
if (szTrackerServers == null) {
throw new MyException("item \"tracker_server\" in " + conf_filename + " not found");
} else {
InetSocketAddress[] tracker_servers = new InetSocketAddress[szTrackerServers.length];
for(int i = 0; i < szTrackerServers.length; ++i) {
String[] parts = szTrackerServers[i].split("\\:", 2);
if (parts.length != 2) {
throw new MyException("the value of item \"tracker_server\" is invalid, the correct format is host:port");
}
tracker_servers[i] = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim()));
}
g_tracker_group = new TrackerGroup(tracker_servers);
g_tracker_http_port = iniReader.getIntValue("http.tracker_http_port", 80);
g_anti_steal_token = iniReader.getBoolValue("http.anti_steal_token", false);
if (g_anti_steal_token) {
g_secret_key = iniReader.getStrValue("http.secret_key");
}
}
}
//添加的这一个新方法
public static void init(String conf_filename,FastdfsProperties properties) throws IOException, MyException {
g_connect_timeout = properties.getConnectTimeout();
if (g_connect_timeout < 0) {
g_connect_timeout = 5;
}
g_connect_timeout *= 1000;
g_network_timeout = properties.getNetworkTimeout();
if (g_network_timeout < 0) {
g_network_timeout = 30;
}
g_network_timeout *= 1000;
g_charset = properties.getCharset();
if (g_charset == null || g_charset.length() == 0) {
g_charset = "ISO8859-1";
}
String[] szTrackerServers = getTrackerServerValues(properties.getTrackerServer());
if(szTrackerServers == null){
throw new MyException("item \"tracker_server\" in " + conf_filename + " not found");
}else{
InetSocketAddress[] tracker_servers = new InetSocketAddress[szTrackerServers.length];
for(int i = 0; i < szTrackerServers.length; ++i) {
String[] parts = szTrackerServers[i].split("\\:", 2);
if (parts.length != 2) {
throw new MyException("the value of item \"tracker_server\" is invalid, the correct format is host:port");
}
tracker_servers[i] = new InetSocketAddress(parts[0].trim(), Integer.parseInt(parts[1].trim()));
}
g_tracker_group = new TrackerGroup(tracker_servers);
g_tracker_http_port = properties.getTrackerHttpPort();
g_anti_steal_token = properties.getAntiStealToken();
if (g_anti_steal_token) {
g_secret_key = properties.getSecretKey();
}
}
}
private static String[] getTrackerServerValues(Object obj) {
if (obj == null) {
return null;
} else {
String[] values;
if (obj instanceof String) {
values = new String[]{(String)obj};
return values;
} else {
Object[] objs = ((ArrayList)obj).toArray();
values = new String[objs.length];
System.arraycopy(objs, 0, values, 0, objs.length);
return values;
}
}
}
public static Socket getSocket(String ip_addr, int port) throws IOException {
Socket sock = new Socket();
sock.setSoTimeout(g_network_timeout);
sock.connect(new InetSocketAddress(ip_addr, port), g_connect_timeout);
return sock;
}
public static Socket getSocket(InetSocketAddress addr) throws IOException {
Socket sock = new Socket();
sock.setSoTimeout(g_network_timeout);
sock.connect(addr, g_connect_timeout);
return sock;
}
public static int getG_connect_timeout() {
return g_connect_timeout;
}
public static void setG_connect_timeout(int connect_timeout) {
g_connect_timeout = connect_timeout;
}
public static int getG_network_timeout() {
return g_network_timeout;
}
public static void setG_network_timeout(int network_timeout) {
g_network_timeout = network_timeout;
}
public static String getG_charset() {
return g_charset;
}
public static void setG_charset(String charset) {
g_charset = charset;
}
public static int getG_tracker_http_port() {
return g_tracker_http_port;
}
public static void setG_tracker_http_port(int tracker_http_port) {
g_tracker_http_port = tracker_http_port;
}
public static boolean getG_anti_steal_token() {
return g_anti_steal_token;
}
public static boolean isG_anti_steal_token() {
return g_anti_steal_token;
}
public static void setG_anti_steal_token(boolean anti_steal_token) {
g_anti_steal_token = anti_steal_token;
}
public static String getG_secret_key() {
return g_secret_key;
}
public static void setG_secret_key(String secret_key) {
g_secret_key = secret_key;
}
public static TrackerGroup getG_tracker_group() {
return g_tracker_group;
}
public static void setG_tracker_group(TrackerGroup tracker_group) {
g_tracker_group = tracker_group;
}
}
FastdfsProperties 获取关于fastdfs的配置文件:
@Configuration
@Getter
public class FastdfsProperties {
@Value("${fdfsread_confFileName}")
private String confFileName;
@Value("${storeType}")
private String storeType;
@Value("${connect_timeout:5}")
private int connectTimeout;
@Value("${network_timeout:30}")
private int networkTimeout;
@Value("${charset:ISO8859-1}")
private String charset;
@Value("${tracker_server}")
private Object trackerServer;
@Value("${fdfsread_server}")
private String fdfsreadServer;
@Value("${http.tracker_http_port:80}")
private int trackerHttpPort;
@Value("${tracker_port:22122}")
private String trackerPort;
@Value("${anti_steal_token:false}")
private Boolean antiStealToken;
@Value("${http.secret_key:null}")
private String secretKey;
}
测试效果: