写在前面的话:自己的总结,有什么不对的地方,希望指教交流
spring boot 微服务间文件传输
service端设置:
service端是服务提供者,除了提供接口外,还要封装client SDK 包,用于client端方便调用。我这里用的是swagger-codegen 来通过swagger接口生成swagger.json接口定义文件,然后再通过swagger.json生成client包项目,打包上传,就可以被调用了,节省了很多时间(spring的包管理用的是maven)。
生成swagger.json
在pom.xml build中添加swagger-maven-plugin插件
方便复制,这里粘贴上代码
<plugin>
<groupId>com.github.kongchen</groupId>
<artifactId>swagger-maven-plugin</artifactId>
<version>3.1.7</version>
<configuration>
<apiSources>
<apiSource>
<springmvc>true</springmvc>
<!--swagger接口package路径-->
<locations>xxx.xxx.xxx.controller</locations>
<schemes>http</schemes>
<!--默认请求服务地址-->
<host>localhost:8300</host>
<basePath>/xxx-api</basePath>
<info>
<title>xxx-xxx-service</title>
<version>1.0.0</version>
<description>API For xxx Service</description>
</info>
<!--swagger.json存放路径-->
<swaggerDirectory>${basedir}/target/generated/swagger-ui</swaggerDirectory>
</apiSource>
</apiSources>
</configuration>
<executions>
<execution>
<!--触发该动作的命令,此命令可自定义-->
<phase>compile</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
生成client包项目
这里可以通过swagger-codegen命令行,也可以通过maven插件
在pom.xml build中添加swagger-codegen-maven-plugin插件
方便复制,这里粘贴上代码
<plugin>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-maven-plugin</artifactId>
<version>2.2.3</version>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>generate</goal>
</goals>
<configuration>
<!--swagger.json文件目录-->
<inputSpec>target/generated/swagger-ui/swagger.json</inputSpec>
<output>target/generated/swagger-ui</output>
<language>spring</language>
<library>spring-cloud</library>
<!--生成的包项目的groupId-->
<groupId>xxx.xxx</groupId>
<!--生成的包项目的artifactId-->
<artifactId>xxx-xxx-service-client</artifactId>
<artifactVersion>1.0.0-SNAPSHOT</artifactVersion>
<!--生成的包项目的package-->
<apiPackage>com.xxx.xxx.client.api</apiPackage>
<modelPackage>com.xxx.xxx.client.model</modelPackage>
</configuration>
</execution>
</executions>
</plugin>
生成client包项目
通过mvn install 命令,就可以生成client 包项目
打包上传
这里有一个坑,好像是swagger-codegen留下的,不知道现在改了没
生成的client包中的代码:
@RequestPart注释到client包中成了@RequestParam,我在尝试了很多次,一直报错,在swagger Github issues 中有人提出来了。不知道这个是bug,还是我用的不得法,总之卡在这好久。这里需要把@RequestParam手动改为@RequestPart,然后打包上传。
如果你有私服,可以在client包配置中,添加上你的私服配置,就可以通过mvn deploy 上传了。
web端调用
这里生成的是feign 接口,所以在web端,需要使用feign来进行接口调动。
maven加载包
<dependency>
<groupId>com.xxx</groupId>
<artifactId>xxx-xxx-service-client</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
必要的改动
在包中有feign的默认url,如果想指定url,可以在application中自定义配置,覆盖默认配置即可
自定义encoder:
@Bean
@Primary
@Scope("prototype")
public Encoder multipartFormEncoder() {
return new SpringFormEncoder();
}
指定的此encoder会不会对其他的接口有影响,还不知道,需要遇到时,再想办法解决了。
调用
service和web服务都跑起来,就可以尝试一下,微服务间的文件传输了!!!