企業(yè)信息港網(wǎng)站建沒怎樣自己開發(fā)一款軟件
文章目錄
- 一、需求概述
- 二、開發(fā)方式
- 1、傳統(tǒng)開發(fā)方式
- 2、將接口視為資源文件
- 1.)springmvc工程
- 2.)springboot工程
- 3.)nginx代理
- 三、接口數(shù)據(jù)如何更新
- 1、原始數(shù)據(jù)文件生成接口數(shù)據(jù)
- 1.)定義啟動類
- 2.)啟動監(jiān)聽
- 3.)文件處理
- 4.) 完整代碼
- 2、借助crontab定時執(zhí)行
一、需求概述
通用查詢類接口的需求,在開發(fā)過程中是比較常見的一類需求,一般具有以下的特點:
- 數(shù)據(jù)更新頻率較低
- 無強制鑒權(quán)需求
- 短時間內(nèi)數(shù)據(jù)內(nèi)容固定
二、開發(fā)方式
1、傳統(tǒng)開發(fā)方式
傳統(tǒng)的開發(fā)方式,偏向于遵循MVC 模式
使用@RestController
注解來定義restful接口來進行后續(xù)開發(fā)。此開發(fā)模式大部分開發(fā)人員已經(jīng)司空見慣,駕輕就熟不再詳細(xì)闡述。
2、將接口視為資源文件
具體做法分為以下幾種情況
1.)springmvc工程
springmvc工程配置文件一般為spring-mvc.xml,在此文件添加如下配置指向外部文件目錄
<mvc:resources mapping="/pics/**" location="file:C:\Users\DELL\Pictures\" />
注意:需要以file:絕對文件路徑
方式配置
參考項目:https://gitee.com/00fly/java-code-frame/blob/master/springmvc-dbutils/
2.)springboot工程
springboot工程一般以javaCofig代碼方式定義資源文件映射
@Slf4j
@Configuration
@ConditionalOnWebApplication
public class WebMvcConfig implements WebMvcConfigurer
{....../*** 加載靜態(tài)資源文件或文件映射<br>* 映射路徑優(yōu)先級順序為:META-INF/resources > resources > static > public*/@Overridepublic void addResourceHandlers(final ResourceHandlerRegistry registry){try{registry.addResourceHandler("/pics/**").addResourceLocations("classpath:/data/pic/");registry.addResourceHandler("/upload/**").addResourceLocations("file:" + new File("./upload/").getCanonicalPath() + "/");}catch (IOException e){log.error(e.getMessage(), e);}}
參考項目:https://gitcode.com/00fly/springboot-hello/
示例:https://00fly.online/upload/data.json
3.)nginx代理
nginx代理更方便,只需要在nginx根目錄添加文件即可
典型的nginx配置文件如下:
default.conf
server {listen 80;server_name localhost;#access_log /var/log/nginx/host.access.log main;location / {root /usr/share/nginx/html;index index.html index.htm;}
}
我們只需在目錄 /usr/share/nginx/html 放入資源文件即可。
示例:http://124.71.129.204/data.json
三、接口數(shù)據(jù)如何更新
上部分我們已經(jīng)解決了接口發(fā)布和訪問
的問題,不要忘了:通用查詢類接口仍然有數(shù)據(jù)更新
的需求,我們?nèi)绾蝸斫鉀Q這個需求呢?
1、原始數(shù)據(jù)文件生成接口數(shù)據(jù)
具體概括為:監(jiān)聽原始數(shù)據(jù)文件,當(dāng)數(shù)據(jù)發(fā)生變化時,生成接口數(shù)據(jù)文件,適用于數(shù)據(jù)不定期更新
,
原始數(shù)據(jù):點擊獲取
1.)定義啟動類
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.stream.Collectors;
import java.util.stream.Stream;import org.apache.commons.lang3.StringUtils;import lombok.extern.slf4j.Slf4j;@Slf4j
public class MainRun
{/*** 文件監(jiān)聽程序一直運行* * @param args* @throws IOException*/public static void main(String[] args)throws IOException{// 默認(rèn)監(jiān)聽項目當(dāng)前目錄String path = new File("").getCanonicalPath();URL url = MainRun.class.getProtectionDomain().getCodeSource().getLocation();if (url.getPath().endsWith(".jar")){log.info("please start jar like: java -jar files-listener-0.0.1.jar --path=/work/test");path = Stream.of(args).filter(arg -> arg.contains("--path")).map(arg -> StringUtils.substringAfter(arg, "=")).collect(Collectors.joining());if (StringUtils.isBlank(path) || !new File(path).exists() || !new File(path).isDirectory()){log.error("please check path is a exist directory!");return;}}FileMonitor.initJsonFilesMonitor(path);}
}
2.)啟動監(jiān)聽
import java.io.File;
import java.util.concurrent.TimeUnit;import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;import com.fly.simple.service.JsonDataService;import lombok.extern.slf4j.Slf4j;/*** 監(jiān)聽文件變化*/
@Slf4j
public class FileMonitor
{/*** 初始化文件監(jiān)聽器*/public static void initJsonFilesMonitor(String path){try{log.info("start monitor {} ......", path);FileAlterationObserver observer = new FileAlterationObserver(path, FileFilterUtils.suffixFileFilter(".json"));File dir = new File(path);observer.addListener(new FileAlterationListenerAdaptor(){@Overridepublic void onFileCreate(File file){log.info("★★★★★★★★ {} created.", file.getName());JsonDataService.parseDir(dir);}@Overridepublic void onFileChange(File file){log.info("★★★★★★★★ {} changed.", file.getName());JsonDataService.parseDir(dir);}@Overridepublic void onFileDelete(File file){log.info("★★★★★★★★ {} deleted.", file.getName());JsonDataService.parseDir(dir);}});// 開始監(jiān)聽new FileAlterationMonitor(TimeUnit.SECONDS.toMillis(10), observer).start();}catch (Exception e){log.error(e.getMessage(), e.getCause());}}
}
3.)文件處理
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
import java.util.stream.Collectors;import org.apache.commons.io.FileUtils;import com.fly.simple.entity.Article;
import com.fly.simple.entity.BlogData;
import com.fly.simple.utils.JsonBeanUtils;import lombok.extern.slf4j.Slf4j;/*** JsonData服務(wù)類*/
@Slf4j
public class JsonDataService
{private static File dir = new File(ResourceBundle.getBundle("config").getString("out"));public static void parseDir(File directory){try{// 遍歷目錄下json文件Collection<File> files = FileUtils.listFiles(directory, new String[] {"json"}, false);List<Article> data = files.stream().map(f -> parseToArticles(f)).flatMap(List::stream).distinct().collect(Collectors.toList());FileUtils.writeStringToFile(dir, JsonBeanUtils.beanToJson(data, true), StandardCharsets.UTF_8, false);log.info("articles length : {}", data.size());}catch (IOException e){log.error(e.getMessage(), e);}}/*** 解析File為List* * @param resource* @return*/private static List<Article> parseToArticles(File file){try{String jsonData = FileUtils.readFileToString(file, StandardCharsets.UTF_8);return JsonBeanUtils.jsonToBean(jsonData, BlogData.class, true).getData().getList();}catch (IOException e){log.error(e.getMessage(), e);return Collections.emptyList();}}
}
4.) 完整代碼
https://gitee.com/00fly/effict-side/tree/master/files-listener
2、借助crontab定時執(zhí)行
具體概括為:按照設(shè)定時間點生成接口數(shù)據(jù)文件,適用于數(shù)據(jù)固定周期更新
files-listener
項目根目錄執(zhí)行打包
mvn clean package -f pom-json.xml
執(zhí)行后會在target文件目錄生成files-listener-0.0.1.jar
,將jar上傳到服務(wù)器目錄如:/work/files-listener-0.0.1.jar
后
命令行執(zhí)行
#查看定時任務(wù)
crontab -l#編輯定時任務(wù)
crontab -e
編輯時輸入以下內(nèi)容
0 */12 * * * java -jar /work/files-listener-0.0.1.jar
此命令實現(xiàn),每12小時執(zhí)行一次Jar
不再詳細(xì)闡述,實現(xiàn)思路具體請查閱文章:服務(wù)器docker應(yīng)用一覽
有任何問題和建議,都可以向我提問討論,大家一起進步,謝謝!
-over-