开发工具: eclipse + spring tools 4
sring.io 生成一个web项目,导入eclipse。(配置mvn,导入什么的不说,我也是看的教程)
导入之后,新建一个Controller类
加注解@Controller
新建一个public String GetVersion()方法return 一个url,加注解@RequestMapping(“getVersionInfo”)。
上面是基础操作,下面开始分几种情况讲。
第一种我现在用的实现方式:云服务器+云对象存储服务器
这种情况我只需要返回一个对象存储服务器里的真实下载地址。
这样我们就可以再Controller类中定义2个String,一个用于放域名一个放fileName
然后配置yml,给Controller类加上配置引用。
把yml文件放在服务器启动用bat的同级config目录下。
有新版本上传对象服务器,直接修改配置文件fileName参数,重启服务端,即可。
对象服务器倒闭或者域名回收修改域名参数。
具体示例如下:
Controller类:
@ConfigurationProperties(prefix="get-version-controlloer")
@Controller
public class demoController {
private String CDNurl;
private String fileName;
@ResponseBody
@RequestMapping("getVersionInfo")
//API地址
public String GetVersion() {
return CDNurl+fileName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getCDNurl() {
return CDNurl;
}
public void setCDNurl(String cDNurl) {
CDNurl = cDNurl;
}
}
新建application.yml,注意yml的空格格式还是缩进
server:
port: 8888
get-version-controlloer:
fileName: test
CDNurl: http://demo.test.com/
maven打包jar 部署到服务器,写个bat启动,分分钟。
如果要实现不重启服务端修改fileName 也是有办法的,修改一下
private String path = "E:/apk/";
@ResponseBody
@RequestMapping("getVersionInfo")
//API地址
public String GetVersion() {
File file = new File(path);
getFile(file);
return CDNurl+fileName;
}
private void getFile(File file) {
if(file != null){
File[] f = file.listFiles();
if(f != null){
for(int i=0;i<f.length;i++){
getFile(f[i]);
}
}else{
if(file.getName().contains(".apk")) {
fileName = file.getName();
}
}
}
}
在E盘apk文件夹下放上一个新版本的文件(只需要文件名对即可)每次被get去查这个文件夹下的名字,就不需要重启服务端达到替换更新版本。不过服务器有开销。这样不需要在yml配置fileName,但是可以配置path目录,也如示例可以写死。
如果不用云对象服务器,就要自己实现下载服务,适配我们客户端写法最好再写2个接口
@ResponseBody
@RequestMapping("contentLength")
public long contentLength() {
if(fileName.isEmpty()){
File file = new File(path);
getFile(file);
contentLength = file.length();
}else {
File file = new File(path + "/" + fileName);
contentLength = file.length();
}
return contentLength;
}
@RequestMapping("downApp")
public void Download(HttpServletRequest request,HttpServletResponse response,@RequestHeader(required = false) String range) {
if(fileName.isEmpty()){
File file = new File(path);
getFile(file);
}
FileUtil.downloadFile(request,response, fileName,range);
contentLength 用于返回客户端数据长度,不写你可以直连downApp接口也可以,但是控制台会报一个错误。因为客户端第一次读取一个长度后就断开连接,然后又发起下载。
downloadFile方法参考:spring boot实现断点上传
实现自己服务器下载要上传apk到服务端就不要用配置fileName的方式了。
一个星期学的干货全在这了,第一次写服务端。