JAVA 实现内存管理 和 LOG 保存的 代码

程序的原型是SUN公司的OPENSOURCE里面的一个内存管理工具。我增加了一个功能,就是在C盘建立一个LOG.TXT文件,把内存数据放进去

代码如下:

/*
 * @(#)MemoryMonitor.java 1.3 05/11/17
 *
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

/*
 * @(#)MemoryMonitor.java 1.3 05/11/17
 */

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.Date;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import java.lang.management.*;
import java.util.*;
import java.io.*;

/**
 * Demo code which plots the memory usage by all memory pools.
 * The memory usage is sampled at some time interval using
 * java.lang.management API. This demo code is modified based
 * java2d MemoryMonitor demo.
 */
public class MemoryMonitor extends JPanel {

    static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp");
    // main inferace
    public Surface surf;
    JPanel controls;
    boolean doControls;
    JTextField tf;
    // Get memory pools.
    static java.util.List<MemoryPoolMXBean> mpools =
        ManagementFactory.getMemoryPoolMXBeans();
    // Total number of memory pools.
    static int numPools = mpools.size();
    static String PATH = "C://";
    static String NAME = "log.txt";
    public MemoryMonitor() {
        setLayout(new BorderLayout());
        setBorder(new TitledBorder(new EtchedBorder(), "Memory Monitor"));
        // new the main inferace class and allocate it memory
        add(surf = new Surface());
        controls = new JPanel();
        controls.setPreferredSize(new Dimension(135,80));
        Font font = new Font("serif", Font.PLAIN, 10);
        JLabel label = new JLabel("Sample Rate");
        label.setFont(font);
        label.setForeground(Color.red);
        controls.add(label);
        tf = new JTextField("1000");
        tf.setPreferredSize(new Dimension(45,20));
        controls.add(tf);
        controls.add(label = new JLabel("ms"));
        label.setFont(font);
        label.setForeground(Color.red);
        controls.add(dateStampCB);
        dateStampCB.setFont(font);
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
               removeAll();
               if ((doControls = !doControls)) {
                   surf.stop();
                   add(controls);
               } else {
                   try {
                       surf.sleepAmount = Long.parseLong(tf.getText().trim());
                   } catch (Exception ex) {}
                   surf.start();
                   add(surf);
               }
               validate();
               repaint();
            }
        });
    }

    // main inferace class
    public class Surface extends JPanel implements Runnable {
        // the main Thread of the main inferace class
        public Thread thread;
        // the sleep time
        public long sleepAmount = 1000;
  public int  usageHistCount = 20000;
        private int w, h;
        // The BufferedImage can create image in the system memory
        private BufferedImage bimg;
        // Graphics2D  is the class which can slove and paint 2D image in JPanel
        private Graphics2D big;
        // create the Font which is used by the Programe
        private Font font = new Font("Times New Roman", Font.PLAIN, 11);
        private int columnInc;
        private float usedMem[][];
        private int ptNum[];
        private int ascent, descent;
        private Rectangle graphOutlineRect = new Rectangle();
        private Rectangle2D mfRect = new Rectangle2D.Float();
        private Rectangle2D muRect = new Rectangle2D.Float();
        private Line2D graphLine = new Line2D.Float();
        // give the Color to Graphocs2D class  TODO
        private Color graphColor = new Color(46, 139, 87);
        // give the Color to Graphocs2D class  TODO
        private Color mfColor = new Color(0, 100, 0);
        // storage the memory that has been used
        private String usedStr;
        // arrayList can storge the value that will be write into "log.txt"
        ArrayList arrayList = new ArrayList();
        //the class bulid function
        public Surface() {
            // set the background color
            setBackground(Color.black);
            // add the mouse click event : if the class has been stop , mouse click will start it, converstion also ok
            addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (thread == null) {
                        start();
                    } else {
                        stop();
                    }
                }
            });
     int i = 0;
     usedMem = new float[numPools][];
     ptNum = new int[numPools];
        }
       
            /**
                * create a new File
                * @param filePath
                * @param fileContent
                * @return
            */
             public void createFile(String filePath, String fileName) {
    
                 try {
                     String fileAddress = filePath + "//" +fileName;
                     //filePath = fileAddress .toString();
                     File myFilePath = new File(fileAddress );
                     if (!myFilePath.exists()) {
                        myFilePath.createNewFile();
                      }
                    }
                catch (Exception e) {
                    System.err.println(e);
                    }
    }
       
        /**
            * transfer ArrayList to String[]
            *
            * @param arrayList
        */
        public String[] arrayToStringArray(ArrayList arrayList) {
            int length = 0;
            if (null != arrayList) {
                    length = arrayList.size();
                }
            String[] returnValue = new String[length];
            String temp = new String();
            for (int i = 0; i < arrayList.size(); i++) {
                temp = (String)arrayList.get(i);
                returnValue[i] = temp;
            }
                return returnValue;
        }
       
        /**
         * write into File
         * @param filePath
         * @param fileName
         * @param args
         * @throws IOException
       */
        public  void writeFile(String filePath, String fileName, String args[] )throws
            IOException {
            FileWriter fw = new FileWriter(filePath + fileName);
            PrintWriter out = new PrintWriter(fw);
            for (int i = 0; i < args.length; i++) {
                out.write(args[i]);
                out.println();
                out.flush();
             }
            fw.close();
            out.close();
        }
       
        // Dimension is a class that including the height and width value
        public Dimension getMinimumSize() {
            return getPreferredSize();
        }

        public Dimension getMaximumSize() {
            return getPreferredSize();
        }

        public Dimension getPreferredSize() {
            return new Dimension(135,80);
        }

        // invoke to draw the class(JPanel)   
        public void paint(Graphics g) {
           
            if (big == null) {
                return;
            }

            big.setBackground(getBackground());
            big.clearRect(0,0,w,h);


     h = h / ((numPools + numPools%2) / 2);
     w = w / 2;

     int k=0; // index of memory pool.
     for (int i=0; i < 2;i++) {
        for (int j=0; j < (numPools + numPools%2)/ 2; j++) {
          plotMemoryUsage(w*i,h*j,w,h,k);
   if (++k >= numPools) {
      i = 3;
      j = (numPools + numPools%2)/ 2;
      break;
   }
        }
     }
            g.drawImage(bimg, 0, 0, this);
        }

 public void plotMemoryUsage(int x1, int y1, int x2, int y2, int npool) {

     MemoryPoolMXBean mp = mpools.get(npool);
     float usedMemory =  mp.getUsage().getUsed();
            float totalMemory =  mp.getUsage().getMax();

            // .. Draw allocated and used strings ..
            big.setColor(Color.green);

     // Print Max memory allocated for this memory pool.
            big.drawString(String.valueOf((int)totalMemory/1024) + "K Max ", x1+4.0f, (float) y1 + ascent+0.5f);
            big.setColor(Color.yellow);

     // Print the memory pool name.
            big.drawString(mp.getName(),  x1+x2/2, (float) y1 + ascent+0.5f);

     // Print the memory used by this memory pool.
            usedStr = String.valueOf((int)usedMemory/1024)
                + "K used";
            big.setColor(Color.green);
            big.drawString(usedStr, x1+4, y1+y2-descent);

            // Calculate remaining size
            float ssH = ascent + descent;
            float remainingHeight = (float) (y2 - (ssH*2) - 0.5f);
            float blockHeight = remainingHeight/10;
            float blockWidth = 20.0f;
            float remainingWidth = (float) (x2 - blockWidth - 10);

            // .. Memory Free ..
            big.setColor(mfColor);
            int MemUsage = (int) (((totalMemory - usedMemory) / totalMemory) * 10);
            int i = 0;
            for ( ; i < MemUsage ; i++) {
                mfRect.setRect(x1+5,(float) y1+ssH+i*blockHeight,
                                blockWidth,(float) blockHeight-1);
                big.fill(mfRect);
            }

            // .. Memory Used ..
            big.setColor(Color.green);
            for ( ; i < 10; i++)  {
                muRect.setRect(x1+5,(float) y1 + ssH+i*blockHeight,
                                blockWidth,(float) blockHeight-1);
                big.fill(muRect);
            }

            // .. Draw History Graph ..
     if (remainingWidth <= 30) remainingWidth = (float)30;
     if (remainingHeight <= ssH) remainingHeight = (float)ssH;
            big.setColor(graphColor);
            int graphX = x1+30;
            int graphY = y1 + (int) ssH;
            int graphW = (int) remainingWidth;
            int graphH = (int) remainingHeight;

            graphOutlineRect.setRect(graphX, graphY, graphW, graphH);
            big.draw(graphOutlineRect);

            int graphRow = graphH/10;

            // .. Draw row ..
            for (int j = graphY; j <= graphH+graphY; j += graphRow) {
                graphLine.setLine(graphX,j,graphX+graphW,j);
                big.draw(graphLine);
            }
       
            // .. Draw animated column movement ..
            int graphColumn = graphW/15;

            if (columnInc == 0) {
                columnInc = graphColumn;
            }

            for (int j = graphX+columnInc; j < graphW+graphX; j+=graphColumn) {
                graphLine.setLine(j,graphY,j,graphY+graphH);
                big.draw(graphLine);
            }

            --columnInc;

            // Plot memory usage by this memory pool. 
            if (usedMem[npool] == null) {
  usedMem[npool] = new float[usageHistCount];
                ptNum[npool] = 0;
            }

     // save memory usage history.
     usedMem[npool][ptNum[npool]] = usedMemory;

            big.setColor(Color.yellow);

     int w1; // width of memory usage history.
     if (ptNum[npool] > graphW) {
         w1 = graphW;
     } else {
  w1 = ptNum[npool];
            }


            for (int j=graphX+graphW-w1, k=ptNum[npool]-w1; k < ptNum[npool];
        k++, j++) {
                 if (k != 0) {
                     if (usedMem[npool][k] != usedMem[npool][k-1]) {
           int h1 = (int)(graphY + graphH * ((totalMemory -usedMem[npool][k-1])/totalMemory));
           int h2 = (int)(graphY + graphH * ((totalMemory -usedMem[npool][k])/totalMemory));
                         big.drawLine(j-1, h1, j, h2);
                     } else {
           int h1 = (int)(graphY + graphH * ((totalMemory -usedMem[npool][k])/totalMemory));
                         big.fillRect(j, h1, 1, 1);
                     }
                 }
            }
            if (ptNum[npool]+2 == usedMem[npool].length) {
                // throw out oldest point
                for (int j = 1;j < ptNum[npool]; j++) {
                     usedMem[npool][j-1] = usedMem[npool][j];
                }
                --ptNum[npool];
            } else {
                ptNum[npool]++;
            }
        }


        public void start() {
            thread = new Thread(this);
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.setName("MemoryMonitor");
            thread.start();
        }


        public synchronized void stop() { 
            thread = null;
            notify();
        }

        public void run() {
            // get the current Thread
            Thread me = Thread.currentThread();
            //
            while (thread == me && !isShowing() || getSize().width == 0) {
                try {
                    thread.sleep(500);
                } catch (InterruptedException e) { return; }
            }
 
            while (thread == me && isShowing()) {
                Dimension d = getSize();
                if (d.width != w || d.height != h) {
                    // the getSize() function can return the width/height from this component 
                    // give the w the value from getSize() function
                    w = d.width;
                    // give the h the value from getSize() function
                    h = d.height;
                    // create the BufferImage by set the width into w and height into h
                    bimg = (BufferedImage) createImage(w, h);
                    // instance the Graphics2D class by using the BufferImage
                    big = bimg.createGraphics();
                    // set the Font of the Graphics2D
                    big.setFont(font);
                    FontMetrics fm = big.getFontMetrics(font);
                    ascent = (int) fm.getAscent();
                    descent = (int) fm.getDescent();
                    }
                 // repaint the image  
                repaint();
               
                try {
                    // let the thread sleep just 1000 seconds
                    thread.sleep(sleepAmount);
                   } catch (InterruptedException e) {
                     break;
                    }
                 // the panel  [dateStampCB] has been selected
                 // then print the information into the cmd screen
                if (MemoryMonitor.dateStampCB.isSelected()) {
                     System.out.println(new Date().toString() + " " + usedStr);
                     String temp = new String(new Date().toString() + " " + usedStr);
                     arrayList.add(temp); 
                }  
                 
            }
            thread = null;
          
        }
       
       
    }
   
    // Test thread to consume memory
    static class Memeater extends ClassLoader implements Runnable {
 Object y[];
 public Memeater() {}
 public void run() {
     y = new Object[10000000];
     int k =0;
     while(true) {
          if (k == 5000000) k=0;
          y[k++] = new Object();
          try {
       Thread.sleep(20);
          } catch (Exception x){}

   // to consume perm gen storage
          try {
                     // the classes are small so we load 10 at a time
                     for (int i=0; i<10; i++) {
                        loadNext();
                     }
                 } catch (ClassNotFoundException x) {
     // ignore exception
                 }

    }

 }

 Class loadNext() throws ClassNotFoundException {

            // public class TestNNNNNN extends java.lang.Object{
            // public TestNNNNNN();
            //   Code:
            //    0:    aload_0
            //    1:    invokespecial   #1; //Method java/lang/Object."<init>":()V
            //    4:    return
            // }

            int begin[] = {
                0xca, 0xfe, 0xba, 0xbe, 0x00, 0x00, 0x00, 0x30,
                0x00, 0x0a, 0x0a, 0x00, 0x03, 0x00, 0x07, 0x07,
                0x00, 0x08, 0x07, 0x00, 0x09, 0x01, 0x00, 0x06,
                0x3c, 0x69, 0x6e, 0x69, 0x74, 0x3e, 0x01, 0x00,
                0x03, 0x28, 0x29, 0x56, 0x01, 0x00, 0x04, 0x43,
                0x6f, 0x64, 0x65, 0x0c, 0x00, 0x04, 0x00, 0x05,
                0x01, 0x00, 0x0a, 0x54, 0x65, 0x73, 0x74 };

            int end [] = {
                0x01, 0x00, 0x10,
                0x6a, 0x61, 0x76, 0x61, 0x2f, 0x6c, 0x61, 0x6e,
                0x67, 0x2f, 0x4f, 0x62, 0x6a, 0x65, 0x63, 0x74,
                0x00, 0x21, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x04,
                0x00, 0x05, 0x00, 0x01, 0x00, 0x06, 0x00, 0x00,
                0x00, 0x11, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00,
                0x00, 0x05, 0x2a, 0xb7, 0x00, 0x01, 0xb1, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00 };


            // TestNNNNNN

            String name = "Test" + Integer.toString(count++);

            byte value[];
            try {
                value = name.substring(4).getBytes("UTF-8");
            } catch (java.io.UnsupportedEncodingException x) {
                throw new Error();
            }

            // construct class file

            int len = begin.length + value.length + end.length;
            byte b[] = new byte[len];
            int i, pos=0;
            for (i=0; i<begin.length; i++) {
                b[pos++] = (byte)begin[i];
            }
            for (i=0; i<value.length; i++) {
                b[pos++] = value[i];
            }
            for (i=0; i<end.length; i++) {
                b[pos++] = (byte)end[i];
            }

            return defineClass(name, b, 0, b.length);

 }
 static int count = 100000;
 
    }
 
    public static void main(String s[]) {
        final MemoryMonitor demo = new MemoryMonitor();
        WindowListener l = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                demo.surf.createFile(PATH,  NAME);
                String temp[] = demo.surf.arrayToStringArray(demo.surf.arrayList);
               // for (int i = 0; i < temp.length; i ++) {
               //        System.out.println("temp is "+temp[i]);
               //   }
                try {
                         demo.surf.writeFile(PATH,  NAME,  temp);
                      } catch(IOException IOe) {
                            System.err.println(e);
                      }
                demo.surf.arrayList.clear(); 
                System.exit(0);
                }
            public void windowDeiconified(WindowEvent e) { demo.surf.start(); }
            public void windowIconified(WindowEvent e) { demo.surf.stop(); }
        };
        JFrame f = new JFrame("MemoryMonitor");
       
        f.addWindowListener(l);
        f.getContentPane().add("Center", demo);
        f.pack();
        f.setSize(new Dimension(400,500));
        f.setVisible(true);
        demo.surf.start();
 Thread thr = new Thread(new Memeater());
 thr.start();
    }

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
背景 当前互联网企业存在很多业务风险,有些风险(比如薅羊毛)虽然没有sql注入漏洞利用来的直接,但是一直被羊毛党、刷单党光顾的企业长期生存下来的几率会很低! 账号:垃圾注册、撞库、盗号等 交易:盗刷、恶意占用资源、篡改交易金额等 活动:薅羊毛 短信:短信轰炸 项目介绍 实时业务风控系统是分析风险事件,根据场景动态调整规则,实现自动精准预警风险的系统。 本项目只提供实时风控系统框架基础和代码模板。 需要解决的问题 哪些是风险事件,注册、登录、交易、活动等事件,需要业务埋点配合提供实时数据接入 什么样的事件是有风险的,风险分析需要用到统计学,对异常用户的历史数据做统计分析,找出异于正常用户的特征 实时性,风险事件的分析必须毫秒级响应,有些场景下需要尽快拦截,能够给用户止损挽回损失 低误报,这需要人工风控经验,对各种场景风险阈值和评分的设置,需要长期不断的调整,所以灵活的规则引擎是很重要的 支持对历史数据的回溯,能够发现以前的风险,或许能够找到一些特征供参考 项目关键字 轻量级,可扩展,实时的Java业务风控系统 基于Spring boot构建,配置文件能少则少 使用drools规则引擎管理风控规则,原则上可以动态配置规则 使用redis、mongodb做风控计算和事件储存,历史事件支持水平扩展 原理 统计学 次数统计,比如1分钟内某账号的登录次数,可以用来分析盗号等 频数统计,比如1小时内某ip上出现的账号,可以用来分析黄牛党等 最大统计,比如用户交易金额比历史交易都大,可能有风险 最近统计,比如最近一次交易才过数秒,可能机器下单 行为习惯,比如用户常用登录地址,用户经常登录时间段,可以用来分析盗号等 抽象:某时间段,在条件维度(可以是多个维度复合)下,利用统计方法统计结果维度的值。充分发挥你的想象吧! 实时计算 要将任意维度的历史数据(可能半年或更久)实时统计出结果,需要将数据提前安装特殊结果准备好(由于事件的维度数量不固定的,选取统计的维度也是随意的,所以不是在关系数据库中建几个索引就能搞定的),需要利用空间换时间,来降低时间复杂度。 redis redis中数据结构sortedset,是个有序的集合,集合中只会出现最新的唯一的值。利用sortedset的天然优势,做频数统计非常有利。 比如1小时内某ip上出现的账号数量统计: 保存维度 ZADD key score member(时间复杂度:O(M*log(N)), N 是有序集的基数, M 为成功添加的新成员的数量),key=ip,score=时间(比如20160807121314),member=账号。存储时略耗性能。 结构如下: 1.1.1.1 |--账号1 20160807121314 |--账号2 20160807121315 |--账号n 20160807121316 2.2.2.2 |--账号3 20160807121314 |--账号4 20160807121315 |--账号m 20160807121316 计算频数 ZCOUNT key min max(时间复杂度:O(1)),key=ip,min=起始时间,max=截止时间。计算的性能消耗极少,优势明显 redis lua 把保存维度,计算频数,过期维度数据等操作,使用lua脚本结合在一起,可以减少网络IO,提高性能 mongodb mongodb本身的聚合函数统计维度,支持很多比如:max,min,sum,avg,first,last,标准差,采样标准差,复杂的统计方法可以在基础聚合函数上建立,比如行为习惯: getDB().getCollection(collectionName).aggregate( Arrays.asList( match(match) --匹配条件维度 , group("$" + field, Accumulators.sum("_count", 1)) --求值维度的次数 , match(new Document("_count", new Document("$gte", minCount))) --过滤,超过minCount才统计 , sort(new Document("_count", -1)) --对次数进行倒叙排列 ) ); 建议在mongodb聚合的维度上建立索引,这样可以使用内存计算,速度较快。 redis性能优于mo
本文是由笔者2012年学习oracle数据库时编写的学习札记,其中的题目 多数为老师留下的思考题目。 我相信本文会对初学者使用oracle有一个初步的使用印象。右图为我所参 考的书籍。 目录 第一讲 Oacle关系数据库 9 一. Oracle的安装 9 二. 用浏览器进入em 企业管理器 11 三.启动DBCA的方法 11 四.服务设置 11 五. Oracle的卸载 11 六. Oracle数据库的应用系统结构 11 七. 补充资料——oracle安装时出现的问题 12 第二讲 Oacle数据库体系结构 14 一. 物理存储结构——(数据库载体) 14 1.数据文件(.DBF) 14 2.日志文件 (.Log) 14 1) 日志文件 15 2) 数据库工作模式 15 3.控制文件(.ctl) 15 4.参数文件 (.ora) 16 二. 逻辑存储结构 17 1.数据块 (Data Blocks) 17 2.盘区(Extent) 18 3.段 (Segment) 18 4.表空间(Table Spaces) P34 18 三. 内存结构 19 1.数据缓冲区: 内存的40% 19 2.日志缓冲区: 19 3.数据字典缓冲区: 19 4.共享池 内存的10% 19 5.大池 5-10M 20 6.JAVA池 不小于20M 20 7.Streams池 20 8.软件代码区: 20 9.程序全局区(PGA) 20 四. 实例的进程结构(实例=SGA + 后台进程) 20 1.DBWR (数据库写入进程) 21 2.LGWR(日志写入进程) 22 3.ARCH(归档进程)-可选进程 22 4.CKPT(检查点进程)-可选进程 22 5.SMON (系统监控进程) 22 6.PMON (进程监控进程) 22 7.RECO (恢复进程) 22 8. Dnnn (调度进程)-可选进程(略) 22 五. 数据字典 22 第三讲 用户、模式和表 24 一. 用户和模式 24 1.模式 24 2.模式对象 24 3.用户 24 (1)创建用户 24 (2)授权 24 (3)删除用户及该模式下对象 26 二. 表 26 1. 数据类型 26 (1)字符型 26 (2)数值型 26 (3)日期时间型 26 (4)LOB (大型对象) 26 (5)RowID (伪列类型) 27 2. 创建表 27 (1)Create Table 表名 27 (2)在原来已有表上建一个新表(结构和数据) 27 (3)使用OEM建表 27 3.默认值和NULL值 27 三. 修改表 28 四. 删除表 28 五. 数据完整性 28 1.Primary Key 约束 28 2.NOT NULL约束 29 3.Unique 约束 29 4.Foreign Key 约束 29 5.Check约束 (最复杂)列级 | 表级 29 第四讲 SQL基本查询 31 一. SQL语句概述 31 1. SQL简介 31 2. SQL分类 31 3. PL/SQL (Procedure Language) 31 二. SQL*Plus 31 1.启动 SQL*Plus 单行编辑 31 2.启动iSQL*Plus 多行编辑 31 3.退出 32  直接关闭 32  输入:Exit 或 quit 32 三. 本书所使用的示例模式 32 1.Vendition:销售管理系统(11个表)(略) 32 2. School:学生成绩管理系统(6个表) 32 四. SQL SELECT语句 34 1.Select语句的格式 34 2.Select … From … ——选择列(投影) 35 3.Where子句——选择行(选择)数据过滤 35 4.Order By子句 35 5.统计函数——列名应指定别名 35 6. Group By分组 36 7.Having子句 36 8.练习:表的查询 36 五. 在SQL *Plus中使用函数 37 1.字符串函数 37 2.数字函数 37 3.日期时间函数 38 4.转换函数 38 第五讲 修改SQL数据与SQL*Plus命令 40 一.添加数据 40 1.Insert Into 表名 [ 字段列表 ] Values (值) 40 2.向表中插入空值 40 3.从其它表中拷贝数据 40 二. 更新数据 41 三. 删除数据 42 1.Delete 语句 42 2.Truncate 语句 42 四. SQL*Plus命令 42 1.设置环境变量命令 42 (1)Pause 43 (2)pagesize 和 newpage 43 (3)linesize 43 (4)numformat 选项 43 (5)timing 选项 44 2.格式化查询结果命令 44 (1)column : 44 (2)Ttitle 和 Btitle 命令 44 3.文件操作命令 45 (1)保存命令到文件 45 (2)检索命令文件到缓冲区 45 (3)运行命令文件 45 (4)保存查询结果到文件 46 4.交互命令:动态查询 46 (1)定义命令 46 (2)替换符 (用来临时存储有关的数据) 46 5.帮助命令 46 (1)help index 将显示SQL*Plus的所有命令 47 (2)help 命令名称 显示该命令的功能和选项 47 6.其他的SQL*Plus命令 47 (1)退出 SQL> Exit | Quit; 47 (2)清除命令 47 (3)查看表结构信息 47 (4)执行操作系统命令 47 第六讲 高级查询 50 一.简单连接 50 1.简单连接 50 2.表别名 P136 50 3.各个表之间的连接 50 二. 使用Join连接 50 1.内连接 50 (1)等值连接(有相同的,逐个匹配) 50 (2)不等连接 51 (3)自然连接 51 2.外连接 (左、右、完全) 51 3.交叉连接 52 三.集合操作 52 1.Union(并)——结果集相加 “Or” 52 2.Intersect(交) “And” 52 3. Minus(差) 52 四.子查询 53 1.使用的是表中的列 53 (1) IN 53 (2)Exist 53 (3)Some、Any和All 53 五.表的查询练习 54 第七讲 PL/SQL编程基础 56 7.1 PL/SQL 程序结构 56 1.PL/SQL块结构 56 2.PL/SQL块的分类(按照特性划分) 56 7.2变量与常量 56 (一)PL/SQL标识符 (给变量命名) 56 (二)标量变量 56 1.PL/SQL标识符 56 2.变量声明(名称、类型、值) 57 3.常量声明 57 (三)为变量和常量赋值 57 1.赋值的位置 57 2.赋值方式 57 (四)作用域:可以访问该变量的程序部分 58 7.3 PL/SQL 块中的SQL 语句 58 7.4 使用%TYPE和%ROWTYPE类型的变量 58 1.%Type 59 2.%RowType 59 7.5 复合变量 60 1.记录类型(“行”) 60 2.记录表类型(“表” ) 60 (1)使用的原因: 60 (2)定义记录表类型(联合数组) 60 7.6 条件判断语句 61 (一)If语句 61 (二)Case语句 62 7.7循环语句 63 1.“直到”循环 63 2.当型循环(While) 63 3.计数型循环(For) 63 7.8游标 64 (一)隐式游标 64 1.含义: 64 2.游标的属性:(获取游标的状态) 64 3.另一种隐式游标 64 (二)显示游标 64 1.声明 64 2.打开和关闭 65 3.检索数据 65 (三)游标For循环 65 (四)游标变量 (动态游标) 66 1.定义 66 2.声明游标变量 66 3.打开游标变量 66 (五) 使用游标更新数据库 66 7.9 异常处理 66 (一)预定义异常 66 (二)非预定义异常 67 1.声明异常名 67 2.将异常名与标准的Oracle错误号联系起来 67 3.在Exception中对异常做处理 67 (三) 用户自定义异常 68 3.处理异常 68 Exception 68 (四)异常传播 68 1.自定义异常的传播 68 2.声明中的异常 68 (五)使用SQLCODE和SQLERRM 68 第八讲 过程、函数和程序包 72 8.1存储过程(procedure) 72 1.创建 72 2.调用存储过程 72 3.修改(替换同名的存储过程) 73 4.参数 73 (1)In 参数:向过程传入一个值 73 (2)Out参数: 73 (3)In Out参数: 74 (4)默认值 74 5.局部变量和子过程 74 8.2函数(function) 75 1.创建 75 2.调用函数 75 8.3程序包(package) 76 1.规范 76 2.主体 76 3.私有成员 77 4.实例化 77 5.重载 77 6.管理程序包和执行权限 77 8.4依赖性 78 练习 78 第九讲 索 引 80 一.了解索引 80 1.B树索引(Balanced) 80 2.位图索引 80 3.反向索引 81 4.基于函数的索引 81 二. 创建索引 81 1.B树索引 81 2.位图索引 81 3.反向索引 81 4.基于函数的索引 81 三. 索引与约束 82 第十讲 视图、序列和同义词 83 一. 视图 83 1.先关概念 83 2.创建 83 3.修改视图 84 4.检索视图定义 84 5.视图的编译 84 6.视图的删除 84 二. 可更新的视图 84 三. 管理序列 84 1.创建 85 2.伪列 85 3.修改序列 85 4.查询序列 85 5.删除序列 85 四. 管理同义词 85 1.同义词 86 3.分类 86 4.创建 86 5.删除 86 第11讲 触发器 88 一. 触发器的组成 88 1.组成 88 2.事件 89 二.触发器的类型 89 1.DML触发器 89 (1)格式 90 (2)语句级触发器 90 (3)多条件触发的条件谓词 91 (4)行级触发器 92 2.替代触发器(instead of) 92 3.系统事件触发器 93 三.Alter Trigger语句 94 四.与触发器有关的数据字典 95 第12讲 安 全 98 一. 用户账号 98 1.用户配置文件(概要文件) 98 2.监视用户 98 二. 权限管理 99 (一)系统权限 99 (二) 对象权限 ---9种 100 三. 角色管理 101 1.系统预定义角色 101 2.自定义角色 101 3.启用和禁用角色 102 4.修改用户设置的角色 102 5.删除角色 102 四. 练习 102 五. 练习 103 六. 练习 104 七. 练习 105 第13讲 备份与恢复 106 一.数据库备份概述 106 1.备份和恢复 106 2.备份的类型 106 二. 数据库备份模式 106 三. 备份数据库 107 (一)物理备份 107 1.脱机备份 (无成本复制 copy paste) 107 2.联机备份 24*7模式 108 (二)逻辑备份 108 1.Export 导出 108 2.Import 导入 109 四. 数据库手动恢复 109 1. 完全恢复 109
abstract (关键字) 抽象 ['æbstrækt] access vt.访问,存取 ['ækses]'(n.入口,使用权) algorithm n.算法 ['ælgәriðm] Annotation [java] 代码注释 [ænәu'teiʃәn] anonymous adj.匿名的[ә'nɒnimәs]'(反义:directly adv.直接地,立即[di'rektli, dai'rektli]) apply v.应用,适用 [ә'plai] application n.应用,应用程序 [,æpli'keiʃәn]' (application crash 程序崩溃) arbitrary a.任意的 ['ɑ:bitrәri] argument n.参数;争论,论据 ['ɑ:gjumәnt]'(缩写 args) assert (关键字) 断言 [ә'sә:t] ' (java 1.4 之后成为关键字) associate n.关联(同伴,伙伴) [ә'sәuʃieit] attribute n.属性(品质,特征) [ә'tribju:t] boolean (关键字) 逻辑的, 布尔型 call n.v.调用; 呼叫; [kɒ:l] circumstance n.事件(环境,状况) ['sә:kәmstәns] crash n.崩溃,破碎 [kræʃ] cohesion 内聚,黏聚,结合 [kәu'hi:ʒәn] (a class is designed with a single, well-focoused purpose. 应该不止这点) command n. 命令,指令 [kә'mɑ:nd](指挥, 控制) (command-line 命令行) Comments [java] 文本注释 ['kɒments] compile [java] v.编译 [kәm'pail]' Compilation n.编辑[,kɒmpi'leiʃәn] const (保留字) constant n. 常量, 常数, 恒量 ['kɒnstәnt] continue (关键字) coupling 耦合,联结 ['kʌpliŋ] making sure that classes know about other classes only through their APIs. declare [java] 声明 [di'klєә] default (关键字) 默认值; 缺省值 [di'fɒ:lt] delimiter 定义符; 定界符 Encapsulation[java] 封装 (hiding implementation details) Exception [java] 例外; 异常 [ik'sepʃәn] entry n.登录项, 输入项, 条目['entri] enum (关键字) execute vt.执行 ['eksikju:t] exhibit v.显示, 陈列 [ig'zibit] exist 存在, 发生 [ig'zist] '(SQL关键字 exists) extends (关键字) 继承、扩展 [ik'stend] false (关键字) final (关键字) finally (关键字) fragments 段落; 代码块 ['frægmәnt] FrameWork [java] 结构,框架 ['freimwә:k] Generic [java] 泛型 [dʒi'nerik] goto (保留字) 跳转 heap n.堆 [hi:p] implements (关键字) 实现 ['implim
### 回答1: 下面是一个简单的Java代码示例,可以解析log4j格式的日志文件: ```java import java.io.BufferedReader; import java.io.FileReader; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Log4jParser { public static void main(String[] args) { String logFile = "path/to/your/log/file.log"; try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { String line; while ((line = reader.readLine()) != null) { String[] parts = line.split("\\s", 4); // 拆分日志行 if (parts.length >= 4) { String timestamp = parts[0] + " " + parts[1]; // 时间戳 String level = parts[2]; // 日志级别 String message = parts[3]; // 日志消息 Date date = parseTimestamp(timestamp); // 解析时间戳 System.out.printf("%s [%s] %s\n", date, level, message); // 打印解析结果 } } } catch (Exception e) { e.printStackTrace(); } } private static Date parseTimestamp(String timestamp) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); return format.parse(timestamp); } } ``` 在此示例中,我们使用BufferedReader类逐行读取日志文件,并使用String.split()方法拆分每一行,从而获取时间戳、日志级别和日志消息。我们将时间戳转换为Date对象,以便进行进一步的处理和格式化输出。 请注意,这只是一个简单的示例代码,实际的实现可能需要更复杂的逻辑来处理各种情况,例如多行消息或不同的日志级别格式。 ### 回答2: 要解析log4j格式的日志,可以使用Java中的正则表达式和字符串操作来提取日志中的各个字段。 首先,读取log文件并将每行日志存储在字符串数组中。可以使用Java中的文件读取和字符串操作方法来实现这一步骤。 接下来,对每一行日志应用正则表达式来提取需要的字段。log4j的日志格式通常包含时间戳、日志级别和具体日志消息。可以使用正则表达式来匹配这些字段并将其存储在对应的变量中。 例如,可以使用如下的正则表达式来匹配log4j日志的时间戳: String regexTimestamp = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"; 使用Java中的Pattern和Matcher类来进行匹配: Pattern patternTimestamp = Pattern.compile(regexTimestamp); Matcher matcherTimestamp = patternTimestamp.matcher(logLine); 然后,使用matcherTimestamp.find()方法来查找匹配的时间戳,并通过matcherTimestamp.group()方法来获取匹配的结果。 类似地,可以使用类似的步骤来提取日志级别和具体日志消息的字段。 最后,将提取的字段进行处理和存储,可以将它们打印出来或存储到其他地方,根据具体需求进行相应的操作。 以上就是使用Java解析log4j格式日志的一个简单示例。具体实现中可能还需要考虑异常处理、文件读取和写入等其他细节。 ### 回答3: 在Java中解析log4j格式的日志文件,我们可以使用log4j库提供的API方法来实现。以下是一个简单的代码示例: ```java import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.spi.LoggingEvent; import org.apache.log4j.spi.ThrowableInformation; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Log4jParser { public static void main(String[] args) { String logFilePath = "path/to/logfile.log"; parseLog4jLog(logFilePath); } public static void parseLog4jLog(String filePath) { try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) { String line; Logger logger = Logger.getLogger(Log4jParser.class); PatternLayout layout = new PatternLayout(); while ((line = reader.readLine()) != null) { LoggingEvent logEvent = layout.parse(line); String logMessage = logEvent.getMessage().toString(); String logLevel = logEvent.getLevel().toString(); String logTimestamp = logEvent.getTimeStamp() + ""; ThrowableInformation throwableInfo = logEvent.getThrowableInformation(); if (throwableInfo != null) { String exceptionStacktrace = throwableInfo.getThrowableStrRep()[0]; // 对于包含异常信息的log,可以通过 throwableInfo 获取异常栈信息 } // 处理解析的日志信息,可根据需要进行相应的业务逻辑处理 System.out.println("Timestamp: " + logTimestamp); System.out.println("Level: " + logLevel); System.out.println("Message: " + logMessage); } } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码中,我们使用`BufferedReader`从日志文件中逐行读取日志内容。然后,我们通过`PatternLayout`的`parse`方法将每行日志内容解析为`LoggingEvent`对象。通过`LoggingEvent`对象,我们可以获取日志的时间戳、日志级别、日志消息以及可选的异常栈信息。 在代码示例中,我们简单示范了如何处理解析的日志信息,你可以根据实际需求进行业务逻辑处理或其他操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值