Este artigo estuda principalmente o conteúdo relacionado dos exemplos de uso do cliente Java FastDFS, e a implementação específica é a seguinte.
O que é FastDFS?
O FastDFS é um sistema de arquivos distribuído de código aberto escrito no idioma C. O FastDFS é feito sob medida para a Internet, considerando totalmente mecanismos como backup redundante, balanceamento de carga e expansão linear de capacidade e prestando atenção a indicadores como alta disponibilidade e alto desempenho. É fácil criar um cluster de servidor de arquivos de alto desempenho para fornecer upload de arquivos, download e outros serviços usando o FastDFS.
Arquitetura FastDFS
A arquitetura FastDFS inclui servidor rastreador e servidor de armazenamento. O cliente solicita o servidor Tracker para fazer upload e baixar arquivos, e o servidor de armazenamento finalmente fará o upload e o download dos arquivos através do agendamento do servidor do rastreador. A função do servidor Tracker é o balanceamento e a programação de carga. Ao fazer o upload de arquivos através do Tracker Server, você pode encontrar o servidor de armazenamento para fornecer serviços de upload de arquivos de acordo com algumas estratégias. Um rastreador pode ser chamado de servidor de rastreamento ou servidor de despacho. O objetivo do servidor de armazenamento é o armazenamento de arquivos. Os arquivos enviados pelo cliente são armazenados no servidor de armazenamento. O Storage Server não implementa seu próprio sistema de arquivos, mas usa o sistema de arquivos do sistema operacional para gerenciar arquivos. O armazenamento pode ser chamado de servidor de armazenamento.
Exemplo
1. Crie um projeto da web maven chamado
Manager de arquivo: mvNarchetype: create-dgroupId = plataform.activity.Filemanager-DartifactId = FILE-manager-DarchetyeartifactId = maven-arcetype-webapp
2. Defina um arquivo do cliente fastdfs fdfs_client.conf:
class = "Properties" name = "code"> Connect_timeout = 2Network_Timeout = 30CharSet = utf-8http.tracker_http_port = 8080http.anti_steal_token = nohttp.secret_key = fastdfs1234567890Track 192.168.1.156:22122#tracker_server = 192.168.1.188:22122#storage_server = 192.168.1.155:23000#não precisa aqui
3. Defina uma interface de configuração:
pacote com.chuanliu.platform.activity.fm.Manager; importar java.io.serializable; interface pública FileManageConfig estende serializável {public static final string file_default_width = "120"; public static final string file_default_height = "120"; public static final string file_default_author = "diandi"; public static final string protocol = "http: //"; public static final string separador = "/"; public static final string rastrear_ngnix_port = "8080"; public static final string client_config_file = "fdfs_client.conf"; }4. Encapsular um feijão de arquivo FastDFS
pacote com.chuanliu.platform.activity.fm.Manager; public class FastDfsFile implementa FileManageConfig {private estático final serialversionuid = -996760121932438618L; nome de string privado; Byte privado [] conteúdo; Private String ext; Private String Hight = File_Default_Height; Private String Width = File_Default_width; private string autor = file_default_author; public fastdfsfile (nome da string, conteúdo byte [], string ext, altura da string, largura da string, string autor) {super (); this.name = nome; this.content = content; this.ext = ext; this.Height = altura; this.width = width; this.author = autor; } public fastdfsfile (nome da string, conteúdo byte [], string ext) {super (); this.name = nome; this.content = content; this.ext = ext; } public byte [] getContent () {return content; } public void setContent (byte [] content) {this.content = content; } public string getExt () {return ext; } public void SetExt (string ext) {this.ext = ext; } public string getHeight () {return Hight; } public void setheight (altura da string) {this.Height = altura; } public string getWidth () {return width; } public void SetWidth (string width) {this.width = width; } public string getAuthor () {return autor; } public void setauthor (string autor) {this.author = autor; } public string getName () {return name; } public void setName (nome da string) {this.name = name; }}5. Defina a classe Core FileManager, que contém métodos para fazer upload, exclusão e obtenção de arquivos:
pacote com.chuanliu.platform.activity.fm.Manager; importar java.io.file; importar java.io.ioException; importar org.apache.log4j.logger; importação org.csource.common.nameValuepAir; importar Org.csource.fastdfs.clientGalBal.nameValuepAir; importar.csource.fastdfs.clientGalBal; org.csource.fastdfs.serverinfo; importar org.csource.fastdfs.storageclient; importar org.csource.fastdfs.storageServer; importar org.csource.fastdfs.trackerclient; import org.csource.fastdfs.trackersver; com.chuanliu.platform.activity.basic.util.loggerutils; public class FileManager implementa FileManageRerConfig {private estático final serialversionuid = 1L; STOTERSTATER STATERSTATER STATERSTATERTERTERTERTERTERTERSTERGGERGER.GGERGER.GETLOGger (Filemanager.Class); trackerCenterCenterTerCenterTerCenterTerTerTerTerTerTerTerTerTerTerTerTerTerTerTerTerTerTerTerTerTerTerTerTerTer. estorageserver; private estático estorageClient storageClient; static {// inicialize o cliente DFS Fast DFS Configurações Client_config_file; logger.info ("Caminho do arquivo de configuração de DFS rápido:" + fdfsclientConfigFilePath); clientglobal.init (fdfsclientConfigFilePathath); trackerClient = new TrackerClient (); storageServer);} Catch (Exceção e) {LoggerUtils.error (Logger, e);}} public static string upload (FILHDDFSFILE FILE) {LOGGERILTILS.Info (Logger, "Nome do arquivo:" Arquivo + file.getName () + "Arquivo:" File.getContent (). NameValuepair [3]; meta_list [0] = new nameValuepair ("largura", "120"); meta_list [1] = new nameValuepair ("heigth", "120"); meta_list [2] = new nameValuePair ("autor", "Diandi"); null; tente {uploadResults = storageclient.upload_file (file.getContent (), file.getext (), meta_list);} catch (ioexception e) {logger.error ("io excepção quando upload o arquivo:" file.getName (), e); o arquivo: " + file.getName (), e);} logger.info (" upload_file tempo usado: " + (system.currenttimemillis () - starttime) +" ms "); if (uploadResults == null) {loggerUtils.erRor (logger," FILHO FALHA FALHA, Código de erro: "Code:" uploadResults [0]; string remotefilename = uploadResults [1]; string fileAbsolutepath = protocolo + rastrearerver.getinetsocketaddress (). +"group_name: " + groupName + ", remoteFileName:" + " " + remoteFileName);return fileAbsolutePath;}public static FileInfo getFile(String groupName, String remoteFileName) {try {return storageClient.get_file_info(groupName, remoteFileName);}catch (IOException e) {Logger.error ("Exceção de IO: obtenha o arquivo do Fast DFS falhou", e);} Catch (Exceção e) {Logger.error ("Exceção não IO: Obtenha o arquivo do Fast DFS falhou", e);} retornar nulo;} public static void DeLeteFile (groupName stringName, String RemoteFilenMe) RemoteFilename);} Public Static StoreageServer [] getSTorestorAges (String GroupName) lança IoException {return trackerClient.getStoreSorAges (rastrearerver, groupName);} public static serverInfo [] getFetchSorages (string grupo, string RemoteFilame) Owns) TrackerClient.getFetchStorages (TrackerServer, GroupName, RemoteFileName);}}6. Classe de teste de unidade
Gerenciador de pacotes; importar java.io.file; importar java.io.fileInputStream; importar org.csource.fastdfs.fileinfo; importar org.csource.fastdfs.serverinfo; importação org.csource.fastdfs.storageServer; importSerT.junit.stest; com.chuanliu.platform.activity.fm.manager.fastdfsfile; importar com.chuanliu.platform.activity.fm.manager.filemanager;/** * @author josh wang (sheng) * @Email [email protected] */ novo arquivo ("c: //520.jpg"); fileInputStream fis = new FileInputStream (content); byte [] file_buff = null; if (fis! = null) {int len = fis.Available (); file_buff = new Byte [len]; fis.read (FILD_BD); file_buff, "jpg"); string fileAbsolutepath = FileManager.Upload (file); System.out.println (FileAbsolutepath); fis.close ();}@teste public void getFile () lança excepção {fileInfo file = FILEMANAGER.GETFILE ("Grupo",, GetFile (), Exception {fileInfo file = FilManager.getFile ("Grupo",,, GetFile (), Exception {fileInfo File = FILEMANAGER.GETFILE ("Grupo: "M00/00/00/WKGBM1N1-CIANRlMAABYGPYZDLW073.JPG"); Assert.NotNull (FILE); String sourceadddr = file.getSourceIpaddr (); tamanho longo = file.getfilesize (); size.out.println ("ip:"); getStorageServer () lança exceção {storageServer [] ss = FileManager.getStorestorages ("Group1"); Assert.NotNull (ss); para (int k = 0; k <ss.length; k ++) {System.err.println (k + 1 + "." + + ss [k] .getinetsocketAddress (). getAddress (). "M00/00/00/WKGBM1N1-CIANRlMAABYGPYZDLW073.JPG"); Assert.NotNull (servidores); para (int k = 0; k <servers.length; k ++) {System.err.println (k + 1 + "." + Servidors [k]. servidores [k] .getport ());}}}
Resumir
O exposto acima é todo o conteúdo deste artigo sobre o uso do código da instância do cliente Java FastDFS, e espero que seja útil para todos. Amigos interessados podem continuar se referindo a outros tópicos relacionados neste site. Se houver alguma falha, deixe uma mensagem para apontá -la. Obrigado amigos pelo seu apoio para este site!