首先的通过hibernate操作获取数据生成RRd文件:
public RrdGraphDef createImageByRrd(String taskName,String osid,String nodeip,Integer time,String dayTime){
String osName = System.getProperty("os.name");
String baseDir=System.getProperty("java.io.tmpdir");
if(osName.indexOf("Windows")>-1){
baseDir="D:\\tomcat\\temp\\pps_monitor";
}else{
baseDir="/usr/local/tomcat/temp/pps_monitor";
}
String rrdPath=baseDir+File.separator+taskName+File.separator+taskName+"_"+osid+".rrd";
String pngName=baseDir+File.separator+taskName+File.separator+osid+".png";
//默认一天
long startTime=0;
long endTime=0;
if(null != dayTime && !dayTime.equals("")){
String sd = dayTime+" 00:00:00";
String ed = dayTime+" 23:59:59";
startTime = DateUtils.getDateToTimeStamp(DateUtils.toUtilDateFromString(sd, DateUtils.FORMAT1));
endTime = DateUtils.getDateToTimeStamp(DateUtils.toUtilDateFromString(ed, DateUtils.FORMAT1));
}else{
if(time == 1){
startTime = Util.getTime()-86400;
}else if(time == 2){
startTime = Util.getTime()-86400*6;
}else if(time == 3){
startTime = Util.getTime()-86400*30;
}else if(time == 4){
startTime = Util.getTime()-86400*360;
}
endTime = Util.getTime();
}
IJrobinTool tools=new JrobinTools();
try {
File file=new File(rrdPath);
if(file.exists()){
JrobinGraphParam param=new JrobinGraphParam();
param.setRrdPath(rrdPath);
param.setStartTime(startTime);
param.setEndTime(endTime);
param.setPngPath(pngName);
param.setGraphTitle(nodeip+" - "+taskName);
param.setY(taskName);
RrdGraphDef graphDef=tools.graphingObj(param);
SNUM = SNUM + 1;
return graphDef;
}
FNUM = FNUM + 1;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
JrobinTools代码:
package com.pps.maya.service;
import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import org.jrobin.core.ConsolFuns;
import org.jrobin.core.DsDef;
import org.jrobin.core.DsTypes;
import org.jrobin.core.FetchData;
import org.jrobin.core.FetchRequest;
import org.jrobin.core.RrdDb;
import org.jrobin.core.RrdDef;
import org.jrobin.core.RrdException;
import org.jrobin.core.Sample;
import org.jrobin.core.Util;
import org.jrobin.graph.RrdGraph;
import org.jrobin.graph.RrdGraphDef;
import com.pps.maya.util.JdbcTemplete;
import com.pps.tools.util.DateUtils;
public class JrobinTools implements IJrobinTool {
// 默认间隔频率
final static int step = 60;
// 默认从多个数据中取综合值的方式
private static final String DEFAULT_CONSOL_FUN = ConsolFuns.CF_AVERAGE;
//默认数据库名
private static final String DEFAULT_Data_NAME="input";
public JrobinTools() {
super();
}
@Override
public RrdDef createRrdDef(String rootPath, String rrdName, long beginTime) {
RrdDef rrdDef = null;
try {
File file = new File(rootPath);
if (!file.exists())
file.mkdirs();
String rrdPath = rootPath +File.separator+ rrdName + ".rrd";
rrdDef = new RrdDef(rrdPath,step);
rrdDef.setStartTime(beginTime-step);
DsDef dsDef = new DsDef(DEFAULT_Data_NAME, DsTypes.DT_GAUGE,step*10,Double.NaN,Double.NaN);
rrdDef.addDatasource(dsDef);
rrdDef.addArchive(DEFAULT_CONSOL_FUN, 0.5, 1,86400/step); // 输入给数据源的数据每一个都保存下来
rrdDef.addArchive(DEFAULT_CONSOL_FUN,0.5,7,480); //每7笔数据,取平均值,然后保存
rrdDef.addArchive(DEFAULT_CONSOL_FUN,0.5,30,480); //一月
rrdDef.addArchive(DEFAULT_CONSOL_FUN,0.5,360,480); //一年
return rrdDef;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void insertRrdData(String rrdPath,Double value,long collectTimeUnitsSecond) {
RrdDb rrdDb = null;
try {
rrdDb = new RrdDb(rrdPath);
Sample sample = rrdDb.createSample();
System.out.println(rrdDb.getLastUpdateTime());
sample.setTime(collectTimeUnitsSecond);
if (value == null)
value = Double.NaN;
sample.setValue(DEFAULT_Data_NAME, value);
sample.update();
} catch (RrdException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (rrdDb != null)
try {
rrdDb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void insertRrdData(RrdDef rrdDef, Double value,long collectTimeUnitsSecond) {
RrdDb rrdDb = null;
try {
rrdDb = new RrdDb(rrdDef);
Sample sample = rrdDb.createSample();
sample.setTime(collectTimeUnitsSecond);
if (value == null)
value = Double.NaN;
sample.setValue(DEFAULT_Data_NAME, value);
sample.update();
} catch (RrdException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (rrdDb != null)
try {
rrdDb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public RrdGraphDef graphingObj(JrobinGraphParam params){
RrdGraphDef gDef=null;
try {
//图形定义
gDef = new RrdGraphDef();
gDef.setFilename(params.getPngPath());
gDef.setWidth(500);
gDef.setHeight(100);
gDef.setImageFormat("png");
//指定数据的时间跨度
gDef.setTimeSpan(params.getStartTime(),params.getEndTime());
// 不显示JRobin的签名
gDef.setShowSignature(false);
//设置最少值
gDef.setMinValue(0);
//设置Y轴
gDef.setVerticalLabel(params.getY());
//中文字体
gDef.setSmallFont(new Font("Monospaced", Font.PLAIN, 11));
gDef.setLargeFont(new Font("SansSerif", Font.BOLD, 14));
//标题
gDef.setTitle(params.getGraphTitle());
//注释
gDef.comment("From "+params.getStartDate()+" To "+params.getEndDate()+"\\c");
gDef.datasource("input", params.getRrdPath(), "input",DEFAULT_CONSOL_FUN);
gDef.area("input", Color.green, params.getY());
//聚合
gDef.gprint("input", "LAST", "Current: %5.11f");
gDef.gprint("input", "MIN", "Min: %5.1lf");
gDef.gprint("input", "AVERAGE", " Average: %5.1lf");
gDef.gprint("input", "MAX", " Max: %5.1lf");
return gDef;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void fetchRrdData(String filePath, long startTime,
long endTime) {
try {
// open the file
RrdDb rrd = new RrdDb(filePath);
// create fetch request using the database reference
FetchRequest request = rrd.createFetchRequest(DEFAULT_CONSOL_FUN, startTime,endTime);
// execute the request
FetchData fetchData = request.fetchData();
int columnCount = fetchData.getColumnCount();
int rowCount = fetchData.getRowCount();
long[] timestamps = fetchData.getTimestamps();
System.out.println("[data column count:]" + columnCount);
System.out.println("[data row count:]" + rowCount);
// System.out.println("[fetch data dump:]" + fetchData.dump());
// 循环获取数据
double[][] values = fetchData.getValues();
StringBuffer buffer = new StringBuffer("");
for (int row = 0; row < rowCount; row++) {
buffer.append(timestamps[row]);
buffer.append(" "
+ Util.getDate(timestamps[row]).toLocaleString());
buffer.append(": ");
for (int dsIndex = 0; dsIndex < columnCount; dsIndex++) {
buffer.append((values[dsIndex][row]));
buffer.append(" ");
}
buffer.append("\n");
}
System.out.println("[fetch data display :]\n" + buffer);
} catch (Exception e) {
e.printStackTrace();
}
}
}
action 生成图片方法:
/**
* 生成图片流
*/
public void creatImageByTask() {
try {
this.setNum(num);
RrdGraphDef graphDef = webPGService.createImageByRrd(taskName,osid,nodeip,time,dayTime);
RrdGraph graph = new RrdGraph(graphDef);
BufferedImage image = new BufferedImage(graph.getRrdGraphInfo().getWidth(), graph.getRrdGraphInfo().getHeight(),BufferedImage.TYPE_INT_RGB);
graph.render(image.getGraphics());
ServletActionContext.getResponse().setContentType("image/png");
ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();
ImageIO.write(image, "png",out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
页面显示图片方法:
<img src="action名称!creatImageByTask?参数" />
11-12