Java打包
由于发布系统需要上传修改过后的配置文件到服务器上,但是由于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