Java打包
阿新 • • 發佈:2020-08-03
由於釋出系統需要上傳修改過後的配置檔案到伺服器上,但是由於Jenkins的客戶端上傳檔案的功能我暫時還沒有研究出來,所以在Jenkins伺服器上寫一個Java指令碼,監聽埠,來獲取上傳檔案的socket請求。
指令碼採用最簡單的BIO模型,整個程式只有一個執行緒,也就是主執行緒,負責監聽8088埠,接收到socket連線,直接在死迴圈中,進行檔案處理。
public class SocketServer { private ServerSocket serverSocket; private String fileName = "application-prod.yml";private Integer port; private String folder; Logger logger = Logger.getLogger("SocketServer"); public void receive() { String path = folder; while (true) { if (port == null) { break; } System.out.println("--------listen on " + port + "--------");try { Socket socket = serverSocket.accept(); System.out.println(socket.getInetAddress() + ":" + socket.getPort()); InputStream in = socket.getInputStream(); OutputStream out = new FileOutputStream(path + fileName); byte[] bytes = new byte[16 * 1024]; int count; while ((count = in.read(bytes)) > 0) { out.write(bytes, 0, count); } out.close(); in.close(); removeFile(path, fileName); } catch (Exception e) { System.out.println(e.getMessage()); } } } private void removeFile(String path, String fileName) throws IOException { String line = getFirstLine(path); String serviceName = line.substring(2); Files.move(Paths.get(path + "/" + fileName), Paths.get(path + "/" + serviceName + "/ " + fileName), REPLACE_EXISTING); } public String getFirstLine(String path) throws IOException { BufferedReader br = new BufferedReader(new FileReader(path + "/" + fileName)); String line = br.readLine(); br.close(); return line; } public String initServer(Integer port, String folder) { try { this.port = port; this.folder = folder; serverSocket = new ServerSocket(this.port); return "success"; } catch (IOException e) { return e.getMessage(); } } public static void main(String[] args) { SocketServer socketServer = new SocketServer(); if (args.length == 0) { socketServer.logger.log(Level.ALL, "start server"); System.out.println("This run need two parameters. format: java className [port] [config file folder]"); return; } String port = args[0]; String folder = args[1]; if (folder.lastIndexOf("/") + 1 != folder.length()) { folder = folder + "/"; } String message = socketServer.initServer(Integer.valueOf(port), folder); if (message.equals("success")) { socketServer.receive(); } System.out.println("server cannot start logically, because " + message); } }
由於運維要求Java服務需要打成jar包,這樣程序可以管理,因為機器上有很多服務,防止其他人誤殺死該程序。
jar -cvf target_jar_name.jar compiled_class_name.class
如果直接執行,會報錯,錯誤資訊 no main manifest attribute, in SocketServer.jar
這是因為 MANIFEST-MF檔案中少了一個引數,直接編輯jar包,在MANIFEST-MF檔案末尾,加上Main-Class: SocketServer
Error: Could not find or load main class SocketServer.jar