RestTemplate文件上传下载
大苹果

RestTemplate文件上传下载

使用RestTemplate下载文件Stringurl="需要下载的文件地址";HttpHeadersheader=newHttpHeaders();List<MediaType>list=newArrayList<MediaType>();//指定下载文件类型list.add(MediaType.APPLICATION_OCTET_STREAM);header.setAccept(list);HttpEntity<byte[]>request=newHttpEntity<byte[]>(params,header);ResponseEntity<byte[]>response=this.restTemplate.exchange(url,HttpMethod.POST,request,byte[].class);//取得文件字节byte[]result=response.getBody();使用RestTemplate上传文件Stringurl="接收文件的地址";HttpHeadersheaders=newHttpHeaders();//设置请求头headers.setContentType(MediaType.MULTIPART_FORM_DATA);//file为通过表单上传的文件,如果是服务器上的文件,直接通过newFile创建即可。byte[]bytes=file.getBytes();FilefileToSave=newFile(file.getOriginalFilename());//将表单上传的文件写入新创建文件中FileCopyUtils.copy(bytes,fileToSave);//建立需要上传的资源对象FileSystemResourceresource=newFileSystemResource(fileToSave);MultiValueMap<String,Object>param=newLinkedMultiValueMap<>();//指定上传文件所对应的字段及资源param.add("file",resource);HttpEntity<MultiValueMap<String,Object>>httpEntity=newHttpEntity<>(param,headers);//Result为上传返回结果映射类HttpEntity<Result>responseEntity=restTemplate.exchange(url,HttpMethod.POST,httpEntity,Result.class);//上传文件返回的结果responseEntity.getBody();使用poi导出excel字节到浏览器HSSFWorkbookworkbook=newHSSFWorkbook();HSSFSheetsheet=workbook.createSheet("excel");HttpHeadersheader=newHttpHeaders();//指定文件类型header.setContentType(MediaType.APPLICATION_OCTET_STREAM);//指定导出的文件名称header.set("Content-Disposition","attachment;filename=excel.xls");ByteArrayOutputStreamos=newByteArrayOutputStream();try{workbook.write(os);}catch(IOExceptione){e.printStackTrace();}ResponseEntity<byte[]>excelModels=newResponseEntity<>(os.toByteArray(),header,HttpStatus.OK);

JAVA 133 4月前
NodeJs的服务管理之PM2
大苹果

NodeJs的服务管理之PM2

一、简介pm2是一个带有负载均衡功能的应用进程管理器,类似有Supervisor,forever。二、安装LinuxBinaries下载地址:https://nodejs.org/distcdoneinstack/srcwgethttps://nodejs.org/dist/v4.2.4/node-v4.2.4-linux-x64.tar.gztarxzfnode-v4.2.4-linux-x64.tar.gzcpnode-v4.2.4-linux-x64/bin/node/usr/local/bin/cp-Rnode-v4.2.4-linux-x64/lib/node_modules/usr/local/lib/ln-s/usr/local/lib/node_modules/npm/bin/npm-cli.js/usr/local/bin/npmnpminstallpm2@latest-g#安装最新版本pm2模块PS:如果你的主机无法连接公网,先找到能连公网的主机安装上面的方法安装pm2,然后拷贝到你要安装的主机。拷贝如下目录:/usr/local/bin/node/usr/local/lib/node_modules再创建相关软连接三、PM2常用命令假设你现在已经写好了一个app.js的文件,需要启动,你可以使用pm2进行管理1.启动#pm2startapp.js#pm2startapp.js--namemy-api#my-api为PM2进程名称#pm2startapp.js-i0#根据CPU核数启动进程个数#pm2startapp.js--watch#实时监控app.js的方式启动,当app.js文件有变动时,pm2会自动reload2.查看进程#pm2list#pm2show0或者#pm2info0#查看进程详细信息,0为PM2进程id3.监控#pm2monit4.停止#pm2stopall#停止PM2列表中所有的进程#pm2stop0#停止PM2列表中进程为0的进程5.重载#pm2reloadall#重载PM2列表中所有的进程#pm2reload0#重载PM2列表中进程为0的进程6.重启#pm2restartall#重启PM2列表中所有的进程#pm2restart0#重启PM2列表中进程为0的进程7.删除PM2进程#pm2delete0#删除PM2列表中进程为0的进程#pm2deleteall#删除PM2列表中所有的进程8.日志操作#pm2logs[--raw]#Displayallprocesseslogsinstreaming#pm2flush#Emptyalllogfile#pm2reloadLogs#Reloadalllogs9.升级PM2#npminstallpm2@lastest-g#安装最新的PM2版本#pm2updatePM2#升级pm210.更多命令参数请查看帮助#pm2--help四、PM2目录结构默认的目录是:当前用于的家目录下的.pm2目录(此目录可以自定义,请参考:五、自定义启动文件),详细信息如下:$HOME/.pm2#willcontainallPM2relatedfiles$HOME/.pm2/logs#willcontainallapplicationslogs$HOME/.pm2/pids#willcontainallapplicationspids$HOME/.pm2/pm2.log#PM2logs$HOME/.pm2/pm2.pid#PM2pid$HOME/.pm2/rpc.sock#Socketfileforremotecommands$HOME/.pm2/pub.sock#Socketfileforpublishableevents$HOME/.pm2/conf.js#PM2Configuration五、自定义启动文件创建一个test.json的示例文件,格式如下:{"apps":{"name":"test","cwd":"/data/wwwroot/nodejs","script":"./test.sh","exec_interpreter":"bash","min_uptime":"60s","max_restarts":30,"exec_mode":"cluster_mode","error_file":"./test-err.log","out_file":"./test-out.log","pid_file":"./test.pid""watch":false}}说明:apps:json结构,apps是一个数组,每一个数组成员就是对应一个pm2中运行的应用name:应用程序的名称cwd:应用程序所在的目录script:应用程序的脚本路径exec_interpreter:应用程序的脚本类型,这里使用的shell,默认是nodejsmin_uptime:最小运行时间,这里设置的是60s即如果应用程序在60s内退出,pm2会认为程序异常退出,此时触发重启max_restarts设置数量max_restarts:设置应用程序异常退出重启的次数,默认15次(从0开始计数)exec_mode:应用程序启动模式,这里设置的是cluster_mode(集群),默认是forkerror_file:自定义应用程序的错误日志文件out_file:自定义应用程序日志文件pid_file:自定义应用程序的pid文件watch:是否启用监控模式,默认是false。如果设置成true,当应用程序变动时,pm2会自动重载。这里也可以设置你要监控的文件。详细参数列表:见附件八六、实例已上面的test.json为例#cat>/data/wwwroot/nodejs/test.sh<<EOF#!/bin/bashwhile:doecho"Test">>1.logsleep5doneEOF#chmod+xtest.sh#添加执行权限#pm2starttest.json#启动,如下图:#pm2list#查看pm2进程,如下图:七、备注其他可参数见官网:http://pm2.keymetrics.io八、附件FieldTypeExampleDescriptionnamestring"myAPI"nameyourappwillhaveinPM2scriptstring"bin/app.js"pathofyourappargslist["--enable-logs","-n","15"]argumentsgiventoyourappwhenitislaunchednode_argslist["--harmony","--max-stack-size=1024"]argumentsgiventonodewhenitislaunchedcwdstring"/var/www/app/prod"thedirectoryfromwhichyourappwillbelaunchedexec_modestring"cluster""fork"modeisusedbydefault,"cluster"modecanbeconfiguredwithinstancesfieldinstancesnumber4numberofinstancesforyourclusteredapp,0meansasmuchinstancesasyouhaveCPUcores.anegativevaluemeansCPUcores-value(e.g-1ona4coresmachinewillspawn3instances)exec_interpreterstring"node"defaultsto"node".canbe"python","ruby","bash"orwhateverinterpreteryouwishtouse."none"willexecuteyourappasabinaryexecutablelog_date_formatstring"YYYY-MM-DDHH:mmZ"formatinwhichtimestampswillbedisplayedinthelogserror_filestring"/var/log/node-app/node-app.stderr.log"pathtothespecifiederrorlogfile.PM2generatesonebydefaultifnotspecifiedandyoucanfinditbytypingpm2desc<appid>out_filestring"/var/log/node-app/node-app.stdout.log"pathtothespecifiedoutputlogfile.PM2generatesonebydefaultifnotspecifiedandyoucanfinditbytypingpm2desc<appid>pid_filestring"pids/node-geo-api.pid"pathtothespecifiedpidfile.PM2generatesonebydefaultifnotspecifiedandyoucanfinditbytypingpm2desc<appid>merge_logsbooleanfalsedefaultstofalse.iftrue,itwillmergelogsfromallinstancesofthesameappintothesamefilecron_restartstring"10***"acronpatterntorestartyourapp.onlyworksin"cluster"modefornow.soontobeavaiblein"fork"modeaswellwatchbooleantrueenablesthewatchfeature,defaultsto"false".iftrue,itwillrestartyourappeverytimeafilechangeisdetectedonthefolderorsubfolderofyourapp.ignore_watchlist["[\/\\]\./","node_modules"]listofregextoignoresomefileorfoldernamesbythewatchfeaturemin_uptimenumber1000minuptimeoftheapptobeconsideredstarted(i.e.iftheappcrashesinthistimeframe,theappwillonlyberestartedthenumbersetinmax_restarts(default15),afterthatit'serrored)max_restartsnumber10numberofconsecutiveunstablerestarts(lessthan1secintervalorcustomtimeviamin_uptime)beforeyourappisconsiderederroredandstopbeingmax_memory_restartstring"150M"yourappwillberestartedbyPM2ifitexceedstheamountofmemoryspecified.human-friendlyformat:itcanbe"10M","100K","2G"andsoon...envobject{"NODE_ENV":"production","ID":"42"}envvariableswhichwillappearinyourappautorestartbooleanfalsetruebydefault.iffalse,PM2willnotrestartyourappifitcrashesorendspeacefullyvizionbooleanfalsetruebydefault.iffalse,PM2willstartwithoutvizionfeatures(versioningcontrolmetadatas)post_updatelist["npminstall","echolaunchingtheapp"]alistofcommandswhichwillbeexecutedafteryouperformaPull/UpgradeoperationfromKeymetricsdashboardforcebooleantruedefaultstofalse.iftrue,youcanstartthesamescriptseveraltimeswhichisusuallynotallowedbyPM2next_gen_jsbooleantruedefaultstofalse.iftrue,PM2willlaunchyourappusingembeddedBabelJSfeatureswhichmeansyoucanrunES6/ES7javascriptcoderestart_delaynumber4000timetowaitbeforerestartingacrashedapp(inmilliseconds).defaultsto0.

NodeJS,PM2,服务管理Web服务 15993 6年前
nodejs异常处理
大苹果

nodejs异常处理

在nodejs开发中,异常处理十分麻烦。一下代码捕捉不到错误functionasync_error(){setTimeout(function(){thrownewError("Error");},10)}functionrun(){try{async_error();}catch(err){console.log(err);}}run();在回调函数内捕获错误,我们不得不在异步函数内写错误处理语句。functionasync_error(){setTimeout(function(){try{thrownewError("Error");}catch(e){console.log(e);}},10)}async_error();如果函数嵌套过多,就会变成这样foo('a',function(a){if(a.error){thrownewError(a.error);}foo('b',function(b){if(b.error){thrownewError(b.error);}foo('c',function(c){if(c.error){thrownewError(c.error);}console.log(a,b,c);});});});但是,在es6里,这个就变的很简单。function*g(){try{vara=yieldfoo('a');varb=yieldfoo('b');varc=yieldfoo('c');}catch(e){console.log(e);}console.log(a,b,c);}如果我们使用async来控制流程varasync=require('async');async.series([function(cb){cb(null);},function(cb){cb(newError("Error"));}],function(err){console.log(err);});async串行执行函数过程中,一旦错误,就会停止执行剩下的函数,直接执行结果回调函数。这样就统一处理错误,变得很清晰。那么使用promise呢varpromise=newPromise(function(resolve,reject){if(/*异步操作成功*/){resolve(value);}else{reject(error);}});promise.then(function(value){//success},function(value){//failure});promise中每个函数执行都有一个错误处理函数。流程控制库帮助我们简化来错误处理机制。另外,我们也可以用events来帮助触发错误处理函数。varevents=require('events');varutil=require('util');functionA(){events.EventEmitter.call(this);}util.inherits(A,events.EventEmitter);vara=newA();a.on('error',function(e){console.log(e)});a.emit('error',newError('a'));

node,node错误处理,async,yield,promise,error 2578 6年前
共 1 页