Spring Cloud Combat and Thinking (iii) uploading a set of files between MicroServices via Fiegn (bottom)

Source: Internet
Author: User
Tags iterable

Requirements Scenario:

The user invokes the interface of the MicroServices 1 to upload a set of pictures and corresponding descriptive information. Micro-service 1 processing, and then the set of images to the micro-service 2 for processing. Each micro-service can separate different images for different processing.

The previous blog has discussed a solution for passing a set of pictures and corresponding parameters between microservices. Now look at how to differentiate the files within a group. The current project uses "commons-fileupload" and "feign-form" Two libraries for file transfer.

The "commons-fileupload" library can convert http request to "multiparthttpservletrequest "and finally get to the"multipartfile"list:

@RequestMapping (value="/psts/add/insertwithfiles", method =requestmethod.post) PublicObject Pastsaddtripinfo (httpservletrequest request) {//Create a general-purpose multi-part parserCommonsmultipartresolver Multipartresolver =NewCommonsmultipartresolver (Request.getsession (). Getservletcontext ());//convert to multi-part RequestMultiparthttpservletrequest multirequest =(multiparthttpservletrequest) request; Map<string, multipartfile> files =Multirequest.getfilemap ();  for(Map.entry<string, multipartfile>Entry:files.entrySet ()) {System. out. println ("file Key Name:"+ Entry.getkey ());//File Object NameSystem. out. println ("file Original name:"+ Entry.getvalue (). Getoriginalfilename ());//File Original nameSystem. out. println ("file name:"+ Entry.getvalue (). GetName ());//File Object Name}}

"GetName ()"of"multipartfile" can get the name of the object specified in the form form. By agreeing on this name, you can distinguish between different files.

  Select File:  <input type= " file  "  name= "   file1   " /> <br/><br/> & Lt;input type= " file   " name="    file2     "/> <br/><br/> <input type=" 
    submit   " value=  "  upload  /> 

Using the file object name, microservices 1 can be divided into groups of files within the group. MicroServices 1 Micro services 2 Use when uploading a set of files feign-form "library. A solution has been found in the previous Weibo blog. However, the scheme " @RequestPart (value =" files ") multipartfile[] photofiles Span style= "font-family: Arial" > "interface method to limit the object name of this set of files to" files ". Seemingly microservices 2 Only the original name of the file " Getoriginalfilename () to differentiate the files. However, the Convention on file names is detrimental to the user experience.

since microservices 1 has the distinguishing identity of the file, that is, the file object name, and the original name of the file remains unchanged during transmission. You might want to use the object name feign-form " in library package " multipartfile[]

The class that encapsulates "multipartfile[]" is "springmanymultipartfileswriter", which uses the " Springsinglemultipartfilewriter"To do specific encapsulation work. So declare a new class "feignspringsinglemultipartfilewriter" inherits from "Springsinglemultipartfilewriter , and then modify its "write ()" function.

Import Feign.form.multipart.output;import Feign.form.spring.springsinglemultipartfilewriter;import Org.springframework.web.multipart.MultipartFile; Public classFeignspringsinglemultipartfilewriter extends Springsinglemultipartfilewriter { PublicFeignspringsinglemultipartfilewriter () {} @Overrideprotected voidwrite (output output, String key, Object value) throws Exception {Multipartfile file=(multipartfile) value; //File.getname () is a file-differentiated identity         This. Writefilemetadata (output, key,file.getname () + "." + file.getoriginalfilename (), File.getcontenttype ());    Output.write (File.getbytes ()); }}

  

declares a "feignspringmanymultipartfileswriter" class, referencing " Feignspringsinglemultipartfilewriter"class:

Import Feign.form.multipart.abstractwriter;import Feign.form.multipart.output;import Org.springframework.web.multipart.multipartfile;import Java.util.Iterator; Public classFeignspringmanymultipartfileswriter extends Abstractwriter {//reference "Feignspringsinglemultipartfilewriter"    PrivateFinalfeignspringsinglemultipartfilewriter fileWriter = new Feignspringsinglemultipartfilewriter ();  PublicFeignspringmanymultipartfileswriter () {} Public voidwrite (output output, string boundary, string key, Object value) throws Exception {if(value instanceof multipartfile[]) {multipartfile[] files=( multipartfile[]) ((multipartfile[]) value); Multipartfile[] VAR6=files; intVAR7 =files.length;  for(intVAR8 =0; Var8 < VAR7; ++var8) {Multipartfile file=VAR6[VAR8];  This. Filewriter.write (output, boundary, key, file); }        } Else if(value instanceof iterable) {iterable iterable=(iterable) value; Iterator Var11=Iterable.iterator ();  while(Var11.hasnext ()) {Object file=Var11.next ();  This. Filewriter.write (output, boundary, key, file); }        }    }     Publicboolean isapplicable (Object value) {if(Value = =NULL) {            return false; } Else if(value instanceof multipartfile[]) {return true; } Else {            if(value instanceof iterable) {iterable iterable=(iterable) value; Iterator Iterator=Iterable.iterator (); if(Iterator.hasnext () &&iterator.next () instanceof Multipartfile) {                    return true; }            }            return false; }    }}

  

Modify the new "Feignspringformencoder" class in the previous blog , using the " Feignspringmanymultipartfileswriter"replaces the original"springmanymultipartfileswriter"class.

 Public classFeignspringformencoder extends Formencoder { PublicFeignspringformencoder () { This(NewDefault ()); }     PublicFeignspringformencoder (EncoderDelegate) {Super (Delegate); Multipartformcontentprocessor Processor= (multipartformcontentprocessor) This. Getcontentprocessor (Contenttype.multipart); Processor.addwriter (NewSpringsinglemultipartfilewriter ()); //using the new encapsulation class "Feignspringmanymultipartfileswriter"Processor.addwriter (New feignspringmanymultipartfileswriter()); }

at this point, microservices 2 can parse the distinguished identity from the original name of the file and use it. Don't know if there's a simpler way to meet this demand?

Spring Cloud Combat and Thinking (iii) uploading a set of files between MicroServices via Fiegn (bottom)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.